Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/449.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用数组的Javascript搜索字符串_Javascript_Regex_Search_Match - Fatal编程技术网

使用数组的Javascript搜索字符串

使用数组的Javascript搜索字符串,javascript,regex,search,match,Javascript,Regex,Search,Match,我试图根据数组中预定义的单词列表搜索网页正文的文本。然后记录每个单词出现的次数 <script> var str = document.body.innerText; var array = []; array[0] = "Statement"; array[1] = "Documents"; var regexp = new RegExp( '\\b' + array.join('\\b|\\b') + '\\b').test(str); document.write(regex

我试图根据数组中预定义的单词列表搜索网页正文的文本。然后记录每个单词出现的次数

<script>
var str = document.body.innerText;
var array = [];
array[0] = "Statement";
array[1] = "Documents"; 
var regexp = new RegExp( '\\b' + array.join('\\b|\\b') + '\\b').test(str);
document.write(regexp)
</script>
试试这个

n = str.match(new RegExp('\\b(' + arr.join('|') + ')\\b', 'ig')) || []).length;
使用i和g标志生成一个动态正则表达式

新RegExp'\\b'+arr.join'|'+'\\b',ig' 将空数组定义为回退

str.matchregex | |[] 返回结果数组或回退数组的长度

str.matchnew RegExp'\\b'+arr.join'|'+'\\b',ig'| |【】长度;
尝试执行var n=str.matchuse数组here.length;还要检查这个问题:不要使用非标准的innerText。使用textContent.innerText何时成为非标准@非多项式内部文本过去是非标准的,但现在情况发生了变化。我讨厌MDN将你重定向到他们俗气的本地化页面,而不是英文版本。我可能没有足够的技能来实现这一点。我想这真的很容易。我会更关注教程。
n = str.match(new RegExp('\\b(' + arr.join('|') + ')\\b', 'ig')) || []).length;