Reputation: 240
I need to change a bunch of different words on a page using jQuery. This is the code I have so far:
(function($) {
var thePage = $("body");
thePage.html(thePage.html().replace([/My Classes/g, 'My Levels'],));
})(jQuery)
How do I modify this code so I can find and replace more words? Lets say I also want to replace "dog" with "cat" and "boy" with "girl".
Upvotes: 1
Views: 6099
Reputation: 5647
What you could do is if you chain the replace values such as:
thePage.html(thePage.html().replace([/My Classes/g, 'My Levels'],))
.replace([/dog/g, 'cat'],))
.replace([/bird/g, 'pen'],));
EDIT:
Here is the updated code with what you've provided on jsfiddle
(function($) {
$(function(){
var thePage = $("body");
thePage.html(thePage.html().replace(/My Classes/g, 'My Levels').replace(/dog/g, 'cat').replace(/bird/g, 'pen'));
});
})(jQuery)
And the jsfiddle link:
Upvotes: 3
Reputation: 191729
You by no means need jQuery
to do this, but it's very difficult to give a good answer without knowing what you are doing. For example, "dog" and "boy" can appear within words. Do you want to replace those instances too, or just the full words? What if they are within attributes -- or are themselves attributes or elements? Is there some sort of priority?
That said, JavaScript String
has no method to replace multiple words at once. You can chain the .replace
, or you can implement something like:
String.prototype.replaceMulti = function (args) {
for (var x = 0; x < args.length; x++) {
this = this.replace(args.from, args.to);
}
}
thePage.html(thePage.html().replaceMulti([{from: /dog/g, to: 'cat'}]);
Upvotes: 0