it is difficult without using a function;
var temp = "", outputArray = [], text = "please help me ".split(""); for(i=0; i < text.length; i++) { console.log(typeof text[i+1]) if(text[i] === " " && (text[i+1] !== " " || typeof text[i+1] === "undefined")) { outputArray.push(temp+=text[i]); temp=""; } else { temp+=text[i]; } } console.log(outputArray);
I do not think that this can help a simple regex. you can use a prototype to use it as your own code ...
String.prototype.splitPreserve = function(seperator) { var temp = "", outputArray = [], text = this.split(""); for(i=0; i < text.length; i++) { console.log(typeof text[i+1]) if(text[i] === seperator && (text[i+1] !== seperator || typeof text[i+1] === "undefined")) { outputArray.push(temp+=text[i]); temp=""; } else { temp+=text[i]; } } return outputArray; } console.log("please help me ".splitPreserve(" "));
source share