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.
var subStr = string.substring(string.indexOf('&') + 1);
View this similar question for other answers:
split string only on first instance of specified character
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"]
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With