I’m attempting to find and replace a string of text, but it doesn’t seem to like when I reference a variable? It works fine if I hardcode the number in there, but returns
missing : after property id
if I try to reference a variable:
var text = "section-1 section_1 section[1]";
var cloneCount = 1;
var cloneUp = 2;
var array = {
"section-"+cloneCount:"section-"+cloneUp,
"section_"+cloneCount:"section_"+cloneUp,
"section\\["+cloneCount:"section\["+cloneUp
};
for (var val in array) {
text = text.replace(new RegExp(val, "gi"), array[val]);
alert(text);
}
Hoping someone here can help?
Your
arrayinitialization is incorrect and should just cause a syntax error. You want this:You can’t use an expression as a key in an object literal, if you need to use an expression to build the key then you have to use the
o[...] = ...syntax.Demo: http://jsfiddle.net/ambiguous/cDthk/