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?

Example:

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

(case insensitive) is this page?

Answer:

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

What javascript and / or jQuery give similar results?

+3


source to share


2 answers


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

$("*").html().match(/abc/gi).length

      

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.
+3


source


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);
alert(count);
alert(count.length);

      

An example is here:

http://jsfiddle.net/csdtesting/a0fkqej0/

Hope it helps!

+1


source







All Articles