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?
for ... in
on arrays. As soon as someone touches the array prototype you will be in for a world of hurt. – cdhowie Aug 16 '11 at 0:30var arr = {...}
. – user113716 Aug 16 '11 at 0:31arr
confused me. :) Still, if someone touches the object prototype, the OP will still have issues. – cdhowie Aug 16 '11 at 0:32