是否有一种方法来检索(开始)字符的位置在一个正则匹配()在Javascript的结果字符串?


当前回答

var str = '我的字符串在这里'; var index = str.match(/hre/).index; 警报(索引),<- 10

其他回答

Exec返回一个带有index属性的对象:

Var match = /bar/.exec("foobar"); If (match) { Console.log ("match found at " + match.index); }

对于多个匹配:

Var re = /bar/g, STR = "foobarfoobar"; While ((match = re.exec(str)) != null) { Console.log ("match found at " + match.index); }

来自developer.mozilla.org文档的String .match()方法:

返回的数组有一个额外的输入属性,该属性包含 被解析的原始字符串。此外,它还有一个索引 属性中匹配的从零开始的索引 字符串。

当处理一个非全局的正则表达式(即,在你的正则表达式上没有g标志)时,.match()返回的值有一个index属性…你要做的就是进入它。

var index = str.match(/regex/).index;

下面是一个例子,展示了它的工作原理:

Var STR = '我的字符串这里'; Var index = str.match(/here/).index; console.log(指数);// <- 10

我已经成功地测试了IE5。

var str = '我的字符串在这里'; var index = str.match(/hre/).index; 警报(索引),<- 10

您可以使用String对象的搜索方法。这将只适用于第一个匹配,但在其他情况下将完成您所描述的工作。例如:

"How are you?".search(/are/);
// 4

在现代浏览器中,您可以使用string.matchAll()来实现这一点。

与RegExp.exec()相比,这种方法的优点是它不依赖于正则表达式是有状态的,就像@Gumbo的答案中那样。

让regexp = /bar/g; 让STR = 'foobarfoobar'; let matches =[…str.matchAll(regexp)]; matches.forEach((match) => { Console.log ("match found at " + match.index); });