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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With