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?
3 Answers 3
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.
7 Comments
'++++++++' one since + needs to be escaped.\Q, \E or Pattern.quote, r'...' or %r{...} in JS.... I'm still looking, though. I'll find something for the OP unless someone beats me to it. :-).indexOf() test for +, then do a .replace(/\+/g,'\\+').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
Comments
var W,H,A,K;
W='123456'.split(''),
H='test this WHAK com www for'.split(' '),
A='2 is a 1 (1ed 6 3 2, 1 6 3 that), 1ing 6 5.3.4';
K=0;for(K in W)A=A.split(W[K]).join(H[K]);
document.write(A);
for ... inon arrays. As soon as someone touches the array prototype you will be in for a world of hurt.var arr = {...}.arrconfused me. :) Still, if someone touches the object prototype, the OP will still have issues.