我有这个例子: https://jsfiddle.net/xqdwL914/1/
<div id="test">bar <i>def</i>ghij<br>bar <i>def</i>ghij</div>
我想找到&#34; bar&#34;多次出现的索引和长度,如下所示:
var node = document.getElementById('test');
var text = node.textContent;
var re = /bar/g;
while ((match = re.exec(text)) != null) {
alert("match found at: " + match.index+ " length: " +match.length);
}
输出:
匹配发现于:0长度:1
匹配发现于:11长度:1
为什么长度为&#34; 1&#34;它应该是&#34; 3&#34;作为单词的三个字符&#34; bar&#34; 以及我如何得到每个匹配词的最后一个索引吧????
答案 0 :(得分:0)
答案 1 :(得分:0)
来自MDN
如果匹配成功,则exec()方法返回一个数组并更新正则表达式对象的属性。返回的数组将匹配的文本作为第一项
var text = 'bar <i>def</i>ghij<br>bar <i>def</i>ghij';
var re = /bar/g;
while ((match = re.exec(text)) != null) {
console.log("match found at: " + match.index+ " length: " +match[0].length);
}
输出:
match found at: 0 length: 3
match found at: 22 length: 3