Javascript replaces globally array

You can use an array to replace:

var array = {"from1":"to1", "from2":"to2"} for (var val in array) text = text.replace(array, array[val]); 

But what if you need to replace globally, i.e. text = text.replace (/ from / g, "to");

The array is quite large, so the script will take up a lot of space if I write "text = text.replace (...)" for each variable.

How can you use an array in this case? "/ from1 / g": "to1" does not work.

+6
javascript replace
source share
3 answers
 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 avoid special characters using a script like this one .

+7
source share

Here is my solution, assuming the string keys in the array should not be escaped.

This is especially effective when the array object 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 Object.keys be available, but you can easily fake it if it is not.

+4
source share

Here's the idiom for a simple, non-RegExp string replaced in JS, so you don't have to worry about special regex characters:

 for (var val in array) text= text.split(val).join(array[val]); 

Please note that there are problems using the object as a general purpose. If someone is monkeys with a prototype object (a bad idea, but some libraries do this), you can get more val s than you wanted; you can use the hasOwnProperty test to avoid this. Plus in IE, if your string came across an Object method, like toString , IE will mysteriously hide it.

In your example, you are fine here, but in the general case, when the strings can be anything, you will need to get around this, either by processing the key strings to avoid collisions, or using a different data structure such as an array of arrays [find, replace] .

+2
source share

All Articles