Javascript: line splitting (but keeping spaces)

How to break a line like this

"please help me " 

to get an array like this:

 ["please ","help ","me "] 

In other words, I get an array that saves space (or spaces)

thanks

+6
source share
2 answers

sort of:

 var str = "please help me "; var split = str.split(/(\S+\s+)/).filter(function(n) {return n}); 

Fiddle

+13
source

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(" ")); 
0
source

Source: https://habr.com/ru/post/949754/


All Articles