是否可以在JS中获取与RegExp匹配的条目数? 让我们假设一个最简单的例子:
var pattern =/\bstring\b/g;
var str = "My the best string comes here. Do you want another one? That will be a string too!";
那么如何获得它的计数呢?如果我尝试使用标准方法 exec():
pattern.exec(str);
...它向我显示了一个数组,包含唯一的匹配条目:
["string"]
该数组的长度为 1,但实际上有 2 个点找到了匹配的条目。
最佳答案
您可以使用 .match() 来实现:
var pattern =/\bstring\b/g;
var str = "My the best string comes here. Do you want another one? That will be a string too!";
alert(str.match(pattern).length);
演示 Fiddle
关于javascript - JS RegExp 匹配条目计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18954153/