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://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string) – 2014-11-21 02:28:40
如果'specialWord'可以包含特殊字符,那么你可能希望在将它传递给RegExp构造函数之前将它转义出来,就像hwnd的回答 – nhahtdh 2014-11-21 02:46:17
或[此答案](http://stackoverflow.com/a/4009787/1338292)和[this one](http ://stackoverflow.com/a/7924240/1338292)。 – 2014-11-21 03:41:07