Split string once in javascript?

You'd want to use String.indexOf('|') to get the index of the first occurrence of '|'.

var i = s.indexOf('|');
var splits = [s.slice(0,i), s.slice(i+1)];

This isn't a pretty approach, but works with decent efficiency:

var string = "1|Ceci n'est pas une pipe: | Oui";
var components = string.split('|');
alert([components.shift(), components.join('|')]​);​​​​​

Here's a quick demo of it


You can use:

var splits = str.match(/([^|]*)\|(.*)/);
splits.shift();

The regex splits the string into two matching groups (parenthesized), the text preceding the first | and the text after. Then, we shift the result to get rid of the whole string match (splits[0]).


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