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
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...