简体   繁体   中英

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.

"Lo ip som.".trim().split('').map(function (ch, i, array) { return ch == ' ' ? array[i - 1] + ' ' : ch })
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;                                
} 

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>"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM