找到capture [JS / RegExp]的起始索引(以字符串形式)

时间:2010-12-06 15:32:21

标签: javascript regex

无论如何我能找到RegExp捕获的索引(以字符串形式)吗?例如...

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

1 个答案:

答案 0 :(得分:2)

indexOf()应该给你你想要的东西:

var index = str.indexOf(match[1]);

jsFiddle example

如果您想循环浏览每个匹配项,则需要为正则表达式添加g修饰符,循环遍历它并每次调用indexOf()。在你的循环中,你将第二个参数传递给indexOf(),告诉它从哪里开始寻找。

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