1

I use the below code for replacing all instances of a character with another:

$("#myContent").each(function () {
    $(this).html($(this).html().replace("1", "一"));
})

$("#myContent").each(function () {
    $(this).html($(this).html().replace("2", "二"));
})

$("#myContent").each(function () {
    $(this).html($(this).html().replace("3", "三"));
})

...

How can I put all these together, something like replacing an array with another?

2
  • 1
    Why are you using each for one selected element? Commented Apr 24, 2013 at 5:16
  • first of all looks like you have multple elements with same ID Commented Apr 24, 2013 at 5:19

3 Answers 3

2

Something like this, untested:

var replacers = {
    '一': /1/gi,
    '二': /2/gi,
    '三': /3/gi
};

var el = $("#myContent"),
    html = el.html();

for (var key in replacers) {
    html = html.replace(replacers[key], key);
}
el.html(html);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, but this does not change every instance of the character. For example, in "2011," only the first "1" will change.
Updated the post. Note that if you're doing this a lot you should probably cache the regexes.
My array only consists of numbers, so basically it has ten members. Is caching still required? In any case, please tell me how should I cache them.
In that case I would just create the regexp up front, updated.
0

Try this way, instead :

var html = $(this).html();

html = html.replace(/1/g, "一");
html = html.replace(/2/g, "二");
html = html.replace(/3/g, "三");

$(this).html(html);

Comments

0

Try

var replacers = {
    '1': '一',
    '2': '二',
    '3': '三'
};

$("#myContent").html(function(index, html){
    $.each(replacers, function(i, v){
        html = html.replace(new RegExp(i, 'g'), v, 'g')
    })
    return html;
});

Demo: Fiddle

1 Comment

This won't change every instance of the character. For example, in "2011," only the first "1" will change.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.