user1217340
user1217340

Reputation: 29

Count and label each time a word is used

I would like to find and count the word "Dog" in the text of a HTML page then update the word with the # in front:

Original:
The dog chased the cat. The cat killed the dog.

Modified:
The 1dog chased the cat. The cat killed the 2dog.

This is what I have so far that isn't working:

var str = 'Dog';  
int count = 0;
var regex;
var regex = new RegExp(str, "g");
for (var i = 0, i < str.length; i++) {
  counter = count++;
  document.body.innerHTML = document.body.innerHTML.replace(regex, counter + "Dog");
}

Upvotes: 0

Views: 55

Answers (3)

horizon0514
horizon0514

Reputation: 21

You should use the replace function like this:

var text = "The dog chased the cat. The cat killed the dog.";
var count = 0;
text.replace(/dog/g,function($0){
    count += 1;
    return count+$0;
})

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148534

You can do this with the Replace function :

var t="The dog chased the cat. The cat killed the dog. so why the dog is eating a dog ?"

i=1;
t=t.replace(/(dog)/ig, function replacer(match, p1) 
  {
   return (i++)+p1;
  });

console.log(t)

Result :

The 1dog chased the cat. The cat killed the 2dog. so why the 3dog is eating a 4dog ?

(edited to to 1 based counting )

Upvotes: 1

Amadan
Amadan

Reputation: 198334

A trivial change to your code will bring you to a working (I think), but not very good solution:

var count = 0;
document.body.innerHTML = document.body.innerHTML.replace(regex,
  function(match) {
    return ++count + match;
  }
);

Note that you do not need a loop: replace will do the loop for you, as long as you have the /g flag.

A problem with this is that you might change things that shouldn't change, such as element names, attribute names and values, javascript code or style rules. A much better (but somewhat involved) solution is to recurse through DOM looking for text nodes, and performing the replacement on their contents.

Upvotes: 1

Related Questions