Faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 6 people (100%) answered Yes
Recently 6 of 6 people (100%) answered Yes

Entry

How can I count the occurences of a certain word in the body of the document?

Nov 19th, 2001 07:23
Martin Honnen,


With IE4+ and NN6 you can access the text of the body with a range
object. Then you can use regular exression matching to count the word.
With NN4 you can count how often window.find returns true. The start
point for searching depends however from the user selection so this
might not be reliable.
Here is a complete example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
counting words
</title>
<script type="text/javascript">
function countWord (word) {
  var bodyText;
  if (document.body && document.body.createTextRange) 
    bodyText = document.body.createTextRange().text;
  else if (document.createRange) {
    var range = document.createRange();
    range.selectNodeContents(document.body);
    bodyText = range.toString();
  }
  if (typeof bodyText != 'undefined') {
    var matches = bodyText.match(new RegExp(word, "g"));
    return matches ? matches.length : 0;
  }
  else if (document.layers) {
    var count = 0;
    while (window.find(word))
      count++;
    return count;
  }
  else 
    return -1;
}
</script>
<script type="text/javascript">
var aWord = 'Kibo';
</script>
</head>
<body onload="var kibos = countWord('Kibo'); alert(kibos);">
<script type="text/javascript">
var n = Math.floor(Math.random() * 20) + 5;
for (var i = 1; i <= n; i++)
  document.write(i + '.: ' + aWord + ' ');
</script>
</body>
</html>
Note that the range.toString() with NN6 gives the text in all elements
including script elements while range.text in IE ignores script elements
and just returns text that is displayed.