I am trying to search the text of a body of a webpage against a list of predefined words in an array. Then record how many instances of each word appeared.
<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>
That one is only returning true or false. Or is there a way to make this one work?
var str = document.body.innerText;
var n = str.match(use array here)
document.write(n)
Try this
n = str.match(new RegExp('\\b(' + arr.join('|') + ')\\b', 'ig')) || []).length;
make a dynamic Regex with i
and g
flag
new RegExp('\\\\b(' + arr.join('|') + ')\\\\b', 'ig')
define an empty array as fallback
str.match(regex) || []
return the length of the results array or the fallback array
str.match(new RegExp('\\\\b(' + arr.join('|') + ')\\\\b', 'ig')) || []).length;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.