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
you want to do something like.
This is because
/i/grefers to the letter i, not the value of variablei. 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:Here is a working example: http://jsfiddle.net/mFj2f/
In general, though, one should check for all the metacharacters, I think.