Reputation: 152
I want to split the string into letters and keep space in previous letter. For example I have this string "Lo ip som." and I want to get this result ['L', 'o ', 'i', 'p ', 's', 'o', 'm', '.']. The 'o ' have space and the 'p ' has space.
Upvotes: 0
Views: 553
Reputation: 26161
You can do like this
var str = "Lo ip som.",
arr = Array.prototype.reduce.call(str,(p,c) => c == " " ? (p[p.length-1]+=" ",p) : p.concat(c),[]);
document.write("<pre>" + JSON.stringify(arr) + "</pre>");
Upvotes: 0
Reputation: 704
function splitString(str){
str = str.trim();
var length = str.length;
retArr = [];
for(var i = 0; i < length; i++){
if(str[i] === ' '){
retArr[retArr.length - 1] += ' ';
continue;
}
retArr.push(str[i]);
}
return retArr;
}
Upvotes: 1
Reputation:
"Lo ip som.".trim().split('').map(function (ch, i, array) { return ch == ' ' ? array[i - 1] + ' ' : ch })
Upvotes: 2