6

You can use array for replacement:

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, ie text = text.replace(/from/g, "to");

Array is pretty big, so script will take a lot of space if I write "text = text.replace(...)" for every variable.

How can you use array in that case? "/from1/g":"to1" does not working.

Qiao
  • 16,565
  • 29
  • 90
  • 117
  • 2
    Your array is actually an Object object, not an Array object, even if it can be considered as an associative array :) – Luc125 Nov 27 '11 at 12:43
  • Does this answer your question? [Replace multiple strings at once](https://stackoverflow.com/questions/5069464/replace-multiple-strings-at-once) – Stephen M. Harris Oct 28 '20 at 22:18

3 Answers3

7
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.

Fabien Ménager
  • 140,109
  • 3
  • 41
  • 60
  • If the string could contain regexp special characters, don't forget to correctly escape them. – Andy E Jan 14 '10 at 12:43
  • This and the other two solutions on this page work for some cases, but have various issues, including cumulative replacement (which allows replacement strings to be replaced) and breakage from inputs with special characters. **[Here is a more robust solution](https://stackoverflow.com/a/37949642/445295).** – Stephen M. Harris Jul 22 '21 at 14:37
3

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.

Luc125
  • 5,752
  • 34
  • 35
1

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

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

Note there are issues with using an Object as a general purpose lookup. If someone's monkeyed with the Object prototype (bad idea, but some libraries do it) you can get more val​s than you wanted; you can use a hasOwnProperty test to avoid that. Plus in IE if your string happens to clash with a method of Object such as toString, IE will mysteriously hide it.

For your example here you're OK, but as a general case where the strings can be anything, you'd need to work around it, either by processing the key strings to avoid clashes, or by using a different data structure such as an Array of [find, replace] Arrays.

bobince
  • 528,062
  • 107
  • 651
  • 834