javascript:拆分字符串(但保留空格)

时间:2013-07-18 14:54:10

标签: javascript regex split

如何分割像这样的字符串

"please     help me "

这样我得到一个这样的数组:

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

换句话说,我得到一个保留空格(或空格)的数组

由于

2 个答案:

答案 0 :(得分:12)

类似的东西:

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

FIDDLE

答案 1 :(得分:0)

如果不使用函数,这很棘手;

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

我不认为一个简单的正则表达式可以帮助解决这个问题。 你可以像原生代码一样使用原型......

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