2014-11-21 45 views
0

我試圖使用匹配()爲了解析一些文本並返回文本顯示的次數。我這樣做是通過使用全局匹配,然後調用從匹配創建的數組的長度。相反,我只是得到一個單一元素的數組。JS:正則表達式和全局匹配()不創建數組

$('button').click(function() { 
    checkword = "/" + specialWord + "/g"; 
    finalAnswer = userText.match(specialWord); 
    console.log(finalAnswer); 
    $('#answer').html(finalAnswer + '<br>' + finalAnswer.length); 
    return finalAnswer; 
}); 

例如,我在「this is」中搜索'is'應該返回一個長度爲2的數組,對嗎?

小提琴:http://jsfiddle.net/

+0

相關:[?如何計算的串串發生(http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string) – 2014-11-21 02:28:40

+0

如果'specialWord'可以包含特殊字符,那麼你可能希望在將它傳遞給RegExp構造函數之前將它轉義出來,就像hwnd的回答 – nhahtdh 2014-11-21 02:46:17

+0

或[此答案](http://stackoverflow.com/a/4009787/1338292)和[this one](http ://stackoverflow.com/a/7924240/1338292)。 – 2014-11-21 03:41:07

回答

2

使用正規構造函數來做到這一點,你需要改變.match(specialWord)checkword代替。

checkword = new RegExp(specialWord, "g"); 
finalAnswer = userText.match(checkword);