Split string once in javascript?

前端 未结 13 1008
南笙
南笙 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:48

    This one's a little longer, but it works like I believe limit should:

    function split_limit(inString, separator, limit){
        var ary = inString.split(separator);
        var aryOut = ary.slice(0, limit - 1);
        if(ary[limit - 1]){
            aryOut.push(ary.slice(limit - 1).join(separator));
        }
        return aryOut;
    }
    console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 1));
    console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 2));
    console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 3));
    console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 7));
    

    https://jsfiddle.net/2gyxuo2j/

    limit of Zero returns funny results, but in the name of efficiency, I left out the check for it. You can add this as the first line of the function if you need it:

    if(limit < 1) return [];
    

提交回复
热议问题