Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript, how in most effective way get second value from string like "var1-var2"

Tags:

javascript

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!

like image 336
publikz.com Avatar asked Jun 02 '11 16:06

publikz.com


4 Answers

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.

like image 125
maerics Avatar answered Oct 23 '22 19:10

maerics


You just have to omit the "." (dot) and start your array index with 0:

str.split("-", 2)[1];
like image 36
Howard Avatar answered Oct 23 '22 19:10

Howard


I usually use this:

str.split("-", 2).pop()
like image 43
bjornd Avatar answered Oct 23 '22 17:10

bjornd


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.

like image 30
KooiInc Avatar answered Oct 23 '22 18:10

KooiInc