Split string once in javascript?

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

    ES6 syntax allows a different approach:

    function splitOnce(s, on) {
       [first, ...rest] = s.split(on)
       return [first, rest.length > 0? rest.join(on) : null]
    }
    

    Which also handles the eventuality of the string not having a | by returning null rather than an empty string, which is more explicit.

    splitOnce("1|Ceci n'est pas une pipe: | Oui", "|")
    >>> ["1", "Ceci n'est pas une pipe: | Oui"]
    
    splitOnce("Celui-ci n'a pas de pipe symbol!", "|")
    >>> ["Celui-ci n'a pas de pipe symbol!", null]
    

    Pas de pipe? C'est null!

    I added this reply primarily so I could make a pun on the pipe symbol, but also to show off es6 syntax - its amazing how many people still don't use it...

提交回复
热议问题