0

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)
Dante
  • 17
  • 5
  • Try doing `var n = str.match(use array here).length;` – Safirah Jan 29 '17 at 10:27
  • 2
    Also check out this question: http://stackoverflow.com/questions/1072765/count-number-of-matches-of-a-regex-in-javascript – Safirah Jan 29 '17 at 10:29
  • Don't use non-standard `innerText`. Use `textContent`. – Oriol Jan 29 '17 at 10:50
  • 1
    since when is `innerText` non-standard? [`innerText`](https://developer.mozilla.org/de/docs/Web/API/Node/innerText#Browser_Compatibility) – NonPolynomial Jan 29 '17 at 10:53
  • @NonPolynomial `innerText` used to be non-standard but things have changed now. Hate that MDN redirects you to their cheesy localized page rather than the English version. – GOTO 0 Jan 29 '17 at 11:02

1 Answers1

1

Try this

n = str.match(new RegExp('\\b(' + arr.join('|') + ')\\b', 'ig')) || []).length;
  1. make a dynamic Regex with i and g flag

    new RegExp('\\b(' + arr.join('|') + ')\\b', 'ig')
    
  2. define an empty array as fallback

    str.match(regex) || []
    
  3. return the length of the results array or the fallback array

    str.match(new RegExp('\\b(' + arr.join('|') + ')\\b', 'ig')) || []).length;
    
NonPolynomial
  • 329
  • 2
  • 6
  • I'm probably not skilled enough to implement this. I thought it would be really easy. I will hit tutorials a bit more. – Dante Jan 31 '17 at 06:34