Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript split to split string in 2 parts irrespective of number of spit characters present in string

Tags:

javascript

I want to split a string in Javascript using split function into 2 parts.

For Example i have string:

str='123&345&678&910'

If i use the javascripts split, it split it into 4 parts. But i need it to be in 2 parts only considering the first '&' which it encounters.

As we have in Perl split, if i use like:

($fir, $sec) = split(/&/,str,2)

it split's str into 2 parts, but javascript only gives me:

str.split(/&/, 2);
fir=123
sec=345

i want sec to be:

sec=345&678&910

How can i do it in Javascript.

like image 774
kailash19 Avatar asked Jun 22 '12 07:06

kailash19


3 Answers

var subStr = string.substring(string.indexOf('&') + 1);

View this similar question for other answers:

split string only on first instance of specified character

like image 194
infojolt Avatar answered Nov 15 '22 07:11

infojolt


You can use match instead of split:

str='123&345&678&910';
splited = str.match(/^([^&]*?)&(.*)$/);
splited.shift();
console.log(splited);

output:

["123", "345&678&910"]
like image 38
core1024 Avatar answered Nov 15 '22 07:11

core1024


You can remain on the split part by using the following trick:

var str='123&345&678&910',
    splitted = str.split( '&' ),
    // shift() removes the first item and returns it
    first = splitted.shift();

console.log( first ); // "123"
console.log( splitted.join( '&' ) ); // "345&678&910"
like image 21
Florian Margaine Avatar answered Nov 15 '22 06:11

Florian Margaine