JQuery function to find and replace

I use the following script to find and replace text on my website.

$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Check In", "入住"); }); 

But there are hundreds of words to search for and replace. Some of them have the same CSS path. Can you guys tell me how to optimize this script and create a function to pass the CSS path and word to search and replace so that I can eliminate the repetition of the same scripts?

You can also pass a few words to find their replacement text. For an example without record

 $("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Room Type", "入住"); }); $("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Guests", "退房"); }); 

Can i do something like

 $("#content #tablelabel p").text(function (_, ctx) { return ctx.replace({'Room Type': '房间类型','Guests': '房间类型'}); }); 

thanks

+7
jquery
source share
3 answers

You can iterate over the object, replace all the values ​​in it, as

 var tags = { 'Room Type': '入住', 'Guests': '退房' }; $("#content #tablelabel p").text(function(_, ctx) { $.each(tags, function(tag, text) { ctx = ctx.replace(tag, text); }) return ctx; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="content"> <div id="tablelabel"> <p>Room Type</p> <p>Guests</p> </div> </div> 
+5
source share

I had the same desire not so long ago.

Consider this use (which I consider more powerful and flexible):

 //USAGE: var pattern = [ { selectors : ["p",".metoo","em"], find : ["set", "me", "free"], replace : ["#set#", "@ me@ ", ">free<"] }, { selectors : ["h5"], find : ["I", "quick", "easy"], replace : ["^ $1 ^"] //$1 is a token to use matched value } ]; replaceText(pattern); 

As you can see, the function accepts an Array objects that define a group of elements, text for searching and replacing. You can install as many as you want.

Some notes:

  • $1 - will be replaced with the agreed value.
  • replace array must have at least one value - each matched text will be replaced with the corresponding replace text, otherwise the previous one.

Jsnippet demo

And here is the function that implements this:

 var replaceText = function(pat) { var ret = []; for (var i = 0; i < pattern.length; i++) { $(pattern[i].selectors.join(",")).text(function(ind,txt){ for (var j=0; j < pattern[i].find.length; j++) { if (typeof pattern[i].replace[j] !== 'undefined') { rep = pattern[i].replace[j].replace("$1", pattern[i].find[j]); } else if (pattern[i].replace.length) { rep = pattern[i].replace[pattern[i].replace.length-1].replace("$1", pattern[i].find[j]); } else { continue; } txt = txt.replace(pattern[i].find[j], rep); } return txt; }); } }; 
+5
source share
 $("#content #tablelabel p").text( function (_, ctx) { return ctx.replace('Room Type','房间类型').replace('Guests','房间类型'); }); 
+5
source share

All Articles