Mladen Stanojevic
Mladen Stanojevic

Reputation: 152

How to split string into characters but to keep spaces in javascript

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

Answers (3)

Redu
Redu

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

Z.Z.
Z.Z.

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

user4615488
user4615488

Reputation:

"Lo ip som.".trim().split('').map(function (ch, i, array) { return ch == ' ' ? array[i - 1] + ' ' : ch })

Upvotes: 2

Related Questions