jquery find and replace multiple items

2019-08-07 11:08发布

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

});

1条回答
beautiful°
2楼-- · 2019-08-07 11:57

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]);
});
查看更多
登录 后发表回答