Reputation: 175
I have been using javascript to remove or replace certain words from an RSS feed using the following code:
document.body.innerHTML = document.body.innerHTML.replace( /Words to be removed/g, "Words to be replaced");
I was wondering if there was a way to detect a certain word and display a message if it does not exist?
Upvotes: 1
Views: 92
Reputation: 8620
If your regex matches a number of words, I think one possibility here would be to replace the second argument to .replace()
with a function. Then, you can implement some counting yourself based on the word that was replaced.
replacedCounts = {};
"bunch of words".replace(/(bunch|of|words)/, function(replaced) {
var prevCount = replacedCounts[replaced];
if (!prevCount) { prevCount = 0; }
replacedCounts[replaced] = prevCount + 1;
return "replacement string";
}); // result should be: "replacement string replacement string replacement string "
// you can now consult replacedCounts['bunch'], etc, to see how many of each were replaced.
Depending on your exact usage, Praveen's answer may be more useful.
Upvotes: 0
Reputation: 1585
In a similar manner as you have used, you can use the match
method.
var matches = document.body.innerHTML.match(/Word to detect/g);
If there are any matches you'll get an array of values that matched.
if(matches.length > 0)
alert("Found!");
Something like this should work for you.
Upvotes: 2