Javascript JS RegExp匹配项计数
是否可以获得与JS中的RegExp匹配的条目计数? 让我们假设一个最简单的例子:Javascript JS RegExp匹配项计数,javascript,regex,count,exec,match,Javascript,Regex,Count,Exec,Match,是否可以获得与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(): …它显示一个数组,包含唯一匹配的条目: ["string"] 此数组的长度为1,但实际上有2个点找到了匹配的条目
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():
…它显示一个数组,包含唯一匹配的条目:
["string"]
此数组的长度为1,但实际上有2个点找到了匹配的条目。您可以使用以下方法实现:
演示您可以通过以下方式实现:
演示
["string"]
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);