How can I quickly count occurrences of a string in a web page?

Given a local url, how can I quickly count the number of lines of a string abc

on a page using JavaScript and / or jQuery?


For a given URL: American Broadcasting Company (ABC) [Wikipedia] , how many times abc

(case insensitive) is this page?


  • 795 (counting HTML tags)
  • 455 (only for visible text)

What javascript and / or jQuery give similar results?


source to share

2 answers

You should be able to do it in conol or javascript on the page:



This will only give you the text nodes on the page *:

var count = 0;
$("body").contents().filter(function () { return this.nodeType == 3 }).each(function () { var match = this.wholeText.match(/abc/gi); if (match) count += match.length; });


  • Only I can see that the javascript code between the tags is rendered as node text, so it also scans the javascript if the script tags are contained in your tag.


So, try these steps:

1) Gives you all the text on the page.

var temp = $('body').text();


2) the g in the regex says to search for the whole string, not just find the first occurrence

var count = temp.match(/abc/g);


An example is here:

Hope it helps!



All Articles