我在 javascript 中有这样的字符串
var str = "This is my test string is Ingrédients";
子字符串 "Ingrédients"
也可以是 "Ingredients"
如何从上面的字符串中获取子字符串 "Ingrédients"
的索引
通过应用正则表达式 ( Ingr[ée]dients
)
最佳答案
如果您只想查找字符串中第一次出现的正则表达式匹配项,您可以使用搜索
。如果你想找到所有出现的地方,那么你可以使用重复的 exec
并查询匹配的 index
值。
这是一个例子:( see it on ideone.com ):
text = "I'm cooking; these are my Ingredients! I mean Ingrédients, yes!";
// 0123456789012345678901234567890123456789012345678901234567890123
re = /Ingr[ée]dients/g;
print(text.search(re)); // "26"
print(text.search(re)); // "26" again
while (m = re.exec(text)) {
print(m.index);
} // "26", "46"
引用资料
关于javascript - 在 Javascript 正则表达式匹配中查找索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3004871/