javascript replace globally with array
var array = {"from1":"to1", "from2":"to2"}
for (var val in array)
text = text.replace(new RegExp(val, "g"), array[val]);
Edit: As Andy said, you may have to escape the special characters using a script like this one.
Here is my solution, assuming the string keys in array
need not to be escaped.
It is particularly efficient when the object array
is large:
var re = new RegExp(Object.keys(array).join("|"), "g");
var replacer = function (val) { return array[val]; };
text = text.replace(re, replacer);
Note this requires the Object.keys
method to be available, but you can easily shim it if it is not.