Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string once in javascript?

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 limit in split doesn't seem to help...

like image 779
Stavros Korokithakis Avatar asked May 20 '10 23:05

Stavros Korokithakis


People also ask

Can we split string in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a JavaScript expression?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.


2 Answers

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)]; 
like image 166
yarmiganosca Avatar answered Oct 18 '22 15:10

yarmiganosca


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

like image 26
Nick Craver Avatar answered Oct 18 '22 15:10

Nick Craver