[英]Finding index inside a Javascript regular expression match
i had string like this in javascript 我在javascript中有这样的字符串
var str = "This is my test string is Ingrédients";
the substring "Ingrédients"
can be also as "Ingredients"
how to get the index of substring "Ingrédients"
from the above string by applying regular expression ( Ingr[ée]dients
) 子串"Ingrédients"
也可以作为"Ingredients"
如何通过应用正则表达式( Ingr[ée]dients
"Ingrédients"
从上面的字符串中获取子串"Ingrédients"
的索引
If you just want to find the first occurrence of a regex match in a string, you can use search
. 如果您只想在字符串中找到第一次出现的正则表达式匹配,则可以使用search
。 If you want to find all occurrences, then you can use repeated exec
and query the match index
values. 如果要查找所有匹配项,则可以使用重复的exec
并查询匹配index
值。
Here's an example: ( see it on ideone.com ): 这是一个例子:( 在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"
使用搜索:
alert(str.search(/Ingr[ée]dients/));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.