Search code examples
javascriptjqueryinternet-explorertextrange

How to count number of occurances of a text in a Page


var textRange = document.body.createTextRange();
  textRange.collapse(true);
  if( textRange.findText(tex)) {
    textRange.execCommand("BackColor", false, "yellow");
}

The above code is perfect to search for text and highlight it in IE but I want to do a little amendment to count the number of occurrences as well. Like below

textRange.findText(tex).WhichMethod()  Should i use to return me count of occurrences. 

Solution

  • If you just want to count the number of instances of a particular pattern, then something like the following should suit:

    function countString(s) {
      var re = new RegExp(s, 'gi');
      var b = document.body;
    
      // Make an assumption about support for textContent and inerText
      var text = typeof b.textContent == 'string'? b.textContent : b.innerText;
      var matches = text.replace(/\s+/g, ' ').match(re);
    
      return matches? matches.length : 0;
    }