0

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.

2
  • what if there is 2 spaces after letter? Commented May 16, 2016 at 19:54
  • i will have 'o' and two spaces in same string Commented May 16, 2016 at 19:56

3 Answers 3

2
"Lo ip som.".trim().split('').map(function (ch, i, array) { return ch == ' ' ? array[i - 1] + ' ' : ch })
Sign up to request clarification or add additional context in comments.

1 Comment

if you have more than one space between two letter you must call after trim: .replace(/\s+/gm, ' ')
1
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;                                
} 

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.