Split string once in javascript?

前端 未结 13 971
南笙
南笙 2020-11-29 03:23

How can I split a string only once, i.e. make 1|Ceci n\'est pas une pipe: | Oui parse to: [\"1\", \"Ceci n\'est pas une pipe: | Oui\"]?

The

13条回答
  •  無奈伤痛
    2020-11-29 03:56

    If the string doesn't contain the delimiter @NickCraver's solution will still return an array of two elements, the second being an empty string. I prefer the behavior to match that of split. That is, if the input string does not contain the delimiter return just an array with a single element.

    var splitOnce = function(str, delim) {
        var components = str.split(delim);
        var result = [components.shift()];
        if(components.length) {
            result.push(components.join(delim));
        }
        return result;
    };
    
    splitOnce("a b c d", " "); // ["a", "b c d"]
    splitOnce("a", " "); // ["a"]
    

提交回复
热议问题