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('|')]);
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]
).