user10279127
user10279127

Reputation:

Is there a way to count number of occurrences of a string in the DOM? (javascript/jQuery)

Is there a way i can find number of occurrence of a value inside the DOM in javascript or jQuery?

Like for instance if i have a

var x = "myFunc('hello');"

how to count number of occurrences of "myFunc('hello');" in the whole DOM?

Upvotes: 0

Views: 1196

Answers (1)

Barmar
Barmar

Reputation: 781706

You can use a regexp match, and get the length of the array of all matches.

var matches = document.body.innerHTML.match(/myFunc\('hello'\)/g);
var count = matches ? matches.length : 0;

Doing it with a variable:

var myVar = "myFunc\\('hello'\\)";
var re = new RegExp(myVar, "g");
var matches = document.body.innerHTML.match(re);
var count = matches ? matches.length : 0;

Note that you need to escape the backslash in myVar so that it will be passed literally to the RegExp constructor.

See Escape a variable within a Regular Expression for a function that can be used to escape all the special characters in a string before using it as a regexp.

Upvotes: 1

Related Questions