Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple occurence string using array element

I have several strings in an associative array:

    var arr = {
        '============================================': '---------',
        '++++++++++++++++++++++++++++++++++++++++++++': '---------',
        '--------------------------------------------': '---------'
    };

I want to replace occurrences of each key with the corresponding value. What I've come up with is:

    for (var i in arr)
    {
        strX = str.replace(i, arr[i]);

        console.log('arr[\''+i+'\'] is ' + arr[i] + ': ' + strX);
    }

This works, but only on first occurence. If I change the regex to /i/g, the code doesn't work.

for (var i in arr)
{
    strX = str.replace(/i/g, arr[i]);

    console.log('arr[\''+i+'\'] is ' + arr[i] + ': ' + strX);
}

Do you guys know how to work around this?

like image 551
ariefbayu Avatar asked Nov 22 '25 04:11

ariefbayu


2 Answers

Instead of

strX = str.replace(/i/g, arr[i]);

you want to do something like.

strX = str.replace(new RegExp(i, "g"), arr[i]);

This is because /i/g refers to the letter i, not the value of variable i. HOWEVER one of your base string has plus signs, which is a metacharacter in regexes. These have to be escaped. The quickest hack is as follows:

new RegExp(i.replace(/\+/g, "\\+"), "g"), arr[i]);

Here is a working example: http://jsfiddle.net/mFj2f/

In general, though, one should check for all the metacharacters, I think.

like image 106
Ray Toal Avatar answered Nov 24 '25 19:11

Ray Toal


The i in the regex will be the string i, not the variable i. Try instead new RegExp(i,'g'); and you should get the desired results

like image 32
LoveAndCoding Avatar answered Nov 24 '25 19:11

LoveAndCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!