开发者

string.search | number of hits

I'm searching for a number in a string, using the .search string method:

var myString = "20 fur bar 50";
alert(myString.search(/\d/);

This 开发者_运维问答returns the position of the first number: 0. How can I get the position of the second number? Is there a way to find out how many hits there are?


Use match instead and the g (global) flag.

jsFiddle.

If you don't want to match the digits individually, change it to \d+.

jsFiddle.


How can I get the position of the second number?

myString.indexOf(myString.match(/\d/g)[1])

Is there a way to find out how many hits there are?

myString.match(/\d/g).length

Of course, I have hardcoded index 1 above, you have to do proper checks.


If you use exec:

var myString = "20 fur bar 50";
var numberPositions = [];
var numberRe = /\d+/g;
for (var match; (match = numberRe.exec(myString));) {
  numberPositions.push(
      [numberRe.lastIndex - match[0].length, numberRe.lastIndex]);
}

then numberPositions is an array of start (inclusive), end (exclusive) pairs:

[[0,2],[11,13]]

[0,2] is the range of characters (end-exclusive) for 20 and [11,13] is the corresponding range for 50.

The regexp used there is /\d+/ instead of /\d/ so that instead of getting a separate range for 2 and 0 you get one range for the whole integer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜