7

I curreny 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 find and replace. Some of them share the same CSS path. Can you guys please tell me how to optimise that script and create a function to pass the CSS path and word to find and replace so I can eliminate repetition of the same scripts?

Also is it possible to pass multiple words to find with their replacement text. For an example without writing

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

Can I do soemthing like

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

Thanks

1
  • 1
    Why are you doing this using JS and not server side before outputting text in English? Commented Nov 17, 2015 at 1:20

3 Answers 3

5

You can iterate over an object an replace all the values in it like

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Arun. That looks good. Is it possible to pass the CSS path as well? Becuase the CSS path can change for some words. So Ideally I can pass the URL and CSS path to the function and get it replaced. But I dont want to repeat the CSS path if its the same.
What do you mean by CSS path?
5
+25

I had the same desire not long ago.

Consider this Usage (which I find more powerful & 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 of Objects that defines the elements group, the text to find and the replacements. you can set as many as you want.

Some notes:

  1. $1 - will be replaced by the matched value.
  2. replace array must have at least one value - each matched text will be replaced by it corresponding replace text otherwise by the previous one.

JSnippet Demo

And Here is the function that implements that:

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;
        });
    }
}; 

Comments

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

2 Comments

Should be: $('"#content, #tabelabel, p") you missed the coma.
@Shlomi Hassid, the space is intended and has a proper meaning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.