Javascript JS:Regex和global match()未创建数组
我尝试使用match()解析一些文本,并返回文本显示的次数。我使用一个全局匹配,然后调用从匹配创建的数组的长度。相反,我只是得到一个包含单个元素的数组Javascript JS:Regex和global match()未创建数组,javascript,arrays,regex,Javascript,Arrays,Regex,我尝试使用match()解析一些文本,并返回文本显示的次数。我使用一个全局匹配,然后调用从匹配创建的数组的长度。相反,我只是得到一个包含单个元素的数组 $('button').click(function () { checkword = "/" + specialWord + "/g"; finalAnswer = userText.match(specialWord); console.log(finalAnswer); $('#answer').html(f
$('button').click(function () {
checkword = "/" + specialWord + "/g";
finalAnswer = userText.match(specialWord);
console.log(finalAnswer);
$('#answer').html(finalAnswer + '<br>' + finalAnswer.length);
return finalAnswer;
});
$(“按钮”)。单击(函数(){
checkword=“/”+specialWord+“/g”;
finalAnswer=userText.match(specialWord);
console.log(finalAnswer);
$('#answer').html(finalAnswer+'
'+finalAnswer.length);
返回finalAnswer;
});
例如,我在“this is”中搜索“is”应该返回一个长度为2的数组,对吗
Fiddle:使用RegExp构造函数来执行此操作,您需要将
.match(specialWord)
改为checkword
checkword = new RegExp(specialWord, "g");
finalAnswer = userText.match(checkword);
相关:如果
specialWord
可以包含特殊字符,那么您可能希望在将其传递给RegExp构造函数之前对其进行转义,就像hwnd的应答器一样,尤其是。