Nate Allen
Nate Allen

Reputation: 240

Find and Replace more than 1 word?

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

Answers (3)

Bogdan Emil Mariesan
Bogdan Emil Mariesan

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:

http://jsfiddle.net/BEftd/4/

Upvotes: 3

Explosion Pills
Explosion Pills

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

Johno
Johno

Reputation: 1959

Try this elegant solution from over here

for (var val in array)
    text= text.split(val).join(array[val]);

You can define an array of key-value pairs representing your search and replace terms, then loop through it like this. No jQuery needed!

Upvotes: 1

Related Questions