Find the start index (in string) of capture [JS/RegExp]
Is there anyway I can find the index (in string) of my RegExp capture? eg ...
var str = "hello开发者_如何学运维 world";
var regex = /lo (wo)/;
var match = regex.exec(str);
// what I want is something like
var index = match[1].index; // where index = 6
indexOf()
should give you what you want:
var index = str.indexOf(match[1]);
jsFiddle example
If you want to loop through each match, you need to add a g
modifier to your regex, loop through it and call indexOf()
each time. In your loop you pass a second argument to indexOf()
to tell it where to start looking.
var str = "hello world hello world";
var regex = /lo (wo)/g;
var match;
var prevIndex, currIndex;
var indexes = [];
while (match = regex.exec(str)) {
currIndex = str.indexOf(match[1], prevIndex);
indexes.push(currIndex);
prevIndex = regex.lastIndex;
}
jsFiddle example
精彩评论