1

I have a monthly table that needs to be translated for each languages

Something like this (doesnt work obviously)

$('.lang-en #monthly th').each(function() {
    var text = $(this).text();
    $(this).text(text.replace('Tam', 'Jan')); 
    $(this).text(text.replace('Hel', 'Feb')); 
    $(this).text(text.replace('Maa', 'Mar')); 
    $(this).text(text.replace('Huh', 'Apr')); 
    $(this).text(text.replace('Tou', 'May')); 
    $(this).text(text.replace('Kes', 'Jun')); 
    $(this).text(text.replace('Hei', 'Jul')); 
    $(this).text(text.replace('Elo', 'Aug')); 
    $(this).text(text.replace('Syy', 'Sep')); 
    $(this).text(text.replace('Lok', 'Oct')); 
    $(this).text(text.replace('Mar', 'Nov'));
    $(this).text(text.replace('Jou', 'Dec')); 
    $(this).text(text.replace('Yht', 'Total'));

});
4
  • Looks fine, what do you mean exactly by doesnt work obviously ? Commented Jun 8, 2012 at 10:24
  • You say "doesnt work obviously", How so? why doesn't this work? What's the point in this code snippet? Commented Jun 8, 2012 at 10:24
  • As a side note @client, consider caching $(this), it's best practise to do so. Commented Jun 8, 2012 at 10:25
  • possible duplicate of javascript string replace array Commented Dec 11, 2012 at 15:44

1 Answer 1

2

You can maintain a mapping between the original and replacement strings, and pass a function to text():

var mapping = {
    "Tam": "Jan",
    "Hel": "Feb",
    // ...and so on...
};

$("#monthly th").text(function(index, originalText) {
    return mapping[originalText];
});

EDIT: If you want to replace only part of the text, you can use nested arrays rather than an object:

var mapping = [
    ["Tam", "Jan"],
    ["Hel", "Feb"],
    // ...and so on...
];

$("#monthly th").text(function(index, originalText) {
    var pattern = mapping[index];
    return originalText.replace(pattern[0], pattern[1]);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Maybe he has another text in th, e.g. Tou: or Huh:ssa.
@VisioN, good point. I'll update my answer accordingly. Thanks :)

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.