最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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 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!

Share Improve this question edited Jun 2, 2011 at 16:08 hvgotcodes 120k33 gold badges207 silver badges237 bronze badges asked Jun 2, 2011 at 16:07 publikz.compublikz.com 9611 gold badge12 silver badges22 bronze badges 0
Add a comment  | 

9 Answers 9

Reset to default 5

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)

  1. 暂无评论