I know about .split( "-" ,2), but how can i make something like this
var str = "123-341235";
alert( str.split( "-",2 ) . [2] )<--- to get second one (341235) value?
Tnx for help All!
I see two simple solutions, which have roughly the same performance:
var str = "123-341235";
str.split('-')[1]; // => "341235" (slower)
str.slice(str.indexOf('-')+1); // => "341235" (faster)
This jsPerf benchmark shows the "slice/indexOf" solution to be about twice as fast on Chrome and Firefox.
Note that for either solution you'll have to check that the hypen character really exists before retrieving the second part of the string; I would bet that adding the check still leaves the "slice/indexOf" solution to be much faster.
You just have to omit the "." (dot) and start your array index with 0:
str.split("-", 2)[1];
I usually use this:
str.split("-", 2).pop()
In one line:
alert('123-341235'.split('-',2 )[1]);
In two you could've guessed:
var str = "123-341235";
alert( str.split('-',2)[1]) );
Arrays are zero based, meaning that the first element of an array has index 0, the second index 1 and so on. Furthermore, a dot between the array and index value ([i]
) generates an error.
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