开发者

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

I know about .split( "-" ,2), but how can i make something like this

var str = "123-3开发者_如何学Go41235";
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.


This should work:

alert( str.split( "-",2 )[0] + '/' + str.split( "-",2 )[1]);


var str = "123-341235";
alert( (str.split("-"))[1] );
  • remeber that arrays are zero based, so the second number is index 1...


The fastest, IMHO

var str = "123-341235";
alert(str.substr(str.indexOf("-")+1));


the second argument tells split how many splits to perform. See

http://www.w3schools.com/jsref/jsref_split.asp

do

var tokens = str.split("-");
tokens[0] // 123
tokens[1] // 341235

split returns an array of the results, and remember arrays are 0-based, so [0] is the first results and [1] is the second result.


A JavaScript question on SO is never complete without some regular expression overkill :

var tokens = /^\d+-(\d+)$/.exec(str);

if (tokens) {
    console.log(tokens[1]);
}

In hindsight, this allows for format validation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜