2013-09-23 44 views
1

是否有可能獲得與JS中RegExp匹配的條目數? 讓我們假設一個simpliest例如:JS正則表達式匹配項數

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"] 

有此數組的lenght 1,但在現實中有2分找到匹配的條目。

回答

1

可以實現使用.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