javascript计数匹配字符串长度
我举了一个例子: 输出: 在以下位置找到匹配项:0长度:1 在以下位置找到匹配项:11长度:1 为什么长度是“1”它应该是“3”作为单词“bar”的三个字符javascript计数匹配字符串长度,javascript,indexing,match,Javascript,Indexing,Match,我举了一个例子: 输出: 在以下位置找到匹配项:0长度:1 在以下位置找到匹配项:11长度:1 为什么长度是“1”它应该是“3”作为单词“bar”的三个字符 如何获取每个匹配词栏的最后一个索引???返回的match是一个数组。我知道您正在查找第一个位置的匹配字符串的长度(匹配[0]): 来自 如果匹配成功,exec()方法将返回一个数组并更新正则表达式对象的属性。返回的数组将匹配的文本作为第一项 那么我如何计算每次迭代的次数呢?当我像这样使用它时:alert(“在:“+match.index+
如何获取每个匹配词栏的最后一个索引???返回的
match
是一个数组。我知道您正在查找第一个位置的匹配字符串的长度(匹配[0]
):
来自
如果匹配成功,exec()方法将返回一个数组并更新正则表达式对象的属性。返回的数组将匹配的文本作为第一项
那么我如何计算每次迭代的次数呢?当我像这样使用它时:alert(“在:“+match.index+”length:“+text.match(re.length)”找到匹配项);它是无限循环的。。
<div id="test">bar <i>def</i>ghij<br>bar <i>def</i>ghij</div>
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);
}
while ((match = re.exec(text)) != null) {
alert("match found at: " + match.index+ " length: " +match[0].length);
}
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