Specific Solution

You can use a function to replace each one.

var str = "I have a cat, a dog, and a goat.";
var mapObj = {
   cat:"dog",
   dog:"goat",
   goat:"cat"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
  return mapObj[matched];
});

jsfiddle example

Generalizing it

If you want to dynamically maintain the regex and just add future exchanges to the map, you can do this

new RegExp(Object.keys(mapObj).join("|"),"gi"); 

to generate the regex. So then it would look like this

var mapObj = {cat:"dog",dog:"goat",goat:"cat"};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
  return mapObj[matched];
});

And to add or change any more replacements you could just edit the map. 

fiddle with dynamic regex

Making it Reusable

If you want this to be a general pattern you could pull this out to a function like this

function replaceAll(str,mapObj){
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");

    return str.replace(re, function(matched){
        return mapObj[matched.toLowerCase()];
    });
}

So then you could just pass the str and a map of the replacements you want to the function and it would return the transformed string.

fiddle with function

To ensure Object.keys works in older browsers, add a polyfill eg from MDN or Es5.

Answer from Ben McCormick on Stack Overflow
Top answer
1 of 16
641

Specific Solution

You can use a function to replace each one.

var str = "I have a cat, a dog, and a goat.";
var mapObj = {
   cat:"dog",
   dog:"goat",
   goat:"cat"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
  return mapObj[matched];
});

jsfiddle example

Generalizing it

If you want to dynamically maintain the regex and just add future exchanges to the map, you can do this

new RegExp(Object.keys(mapObj).join("|"),"gi"); 

to generate the regex. So then it would look like this

var mapObj = {cat:"dog",dog:"goat",goat:"cat"};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
  return mapObj[matched];
});

And to add or change any more replacements you could just edit the map. 

fiddle with dynamic regex

Making it Reusable

If you want this to be a general pattern you could pull this out to a function like this

function replaceAll(str,mapObj){
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");

    return str.replace(re, function(matched){
        return mapObj[matched.toLowerCase()];
    });
}

So then you could just pass the str and a map of the replacements you want to the function and it would return the transformed string.

fiddle with function

To ensure Object.keys works in older browsers, add a polyfill eg from MDN or Es5.

2 of 16
49

As an answer to:

looking for an up-to-date answer

If you are using "words" as in your current example, you might extend the answer of Ben McCormick using a non capture group and add word boundaries \b at the left and at the right to prevent partial matches.

\b(?:cathy|cat|catch)\b
  • \b A word boundary to prevent a partial match
  • (?: Non capture group
    • cathy|cat|catch match one of the alternatives
  • ) Close non capture group
  • \b A word boundary to prevent a partial match

Example for the original question:

let str = "I have a cat, a dog, and a goat.";
const mapObj = {
  cat: "dog",
  dog: "goat",
  goat: "cat"
};
str = str.replace(/\b(?:cat|dog|goat)\b/gi, matched => mapObj[matched]);
console.log(str);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Example for the example in the comments that not seems to be working well:

let str = "I have a cat, a catch, and a cathy.";
const mapObj = {
  cathy: "cat",
  cat: "catch",
  catch: "cathy"

};
str = str.replace(/\b(?:cathy|cat|catch)\b/gi, matched => mapObj[matched]);
console.log(str);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Discussions

javascript - Replace multiple characters in one replace call - Stack Overflow
You can abstract it into a function ... as key/value pairs instead of a flat array. ... Save this answer. ... Show activity on this post. I don't know if how much this will help but I wanted to remove and from my string ... so basically if you want a limited number of character to be reduced and don't waste time this will be useful. ... Save this answer. ... Show activity on this post. Multiple substrings can be replaced with a simple ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Replace multiple strings at once - Stack Overflow
Using ES6: There are many ways to search for strings and replace in JavaScript. More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - How do I replace multiple items in a string? - Stack Overflow
Starting string: I like [dogs], [cats], and [birds] Final output needed: I like dogs, cats, and birds So basic... More on stackoverflow.com
๐ŸŒ stackoverflow.com
string - Javascript Value Replace for Multiple Values - Stack Overflow
I am trying to replace multiple values in a string with JS replace(). The values that I want to replace include line breaks, &, #, etc... I know how to replace one value: var string = document. More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 23, 2017
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ curriculum help
How do I replace multiple strings in an array of Items - Curriculum Help - The freeCodeCamp Forum
January 16, 2021 - I have this code; let myArray = ['he123llo', 'cats', 'wor123ld', 'dogs']; const result = myArray.map(x =>x .replace('1', '') .replace('2', '') .replace('3', '') .replace('s', '') ); console.log(result); //[ 'hello', 'cat', 'world', ...
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ javascript-replace-multiple-characters-in-string
Replace Multiple Characters in a String using JavaScript | bobbyhadz
str.replace(/[._-]/g, ' '). The first parameter the method takes is a regular expression that can match multiple characters. The method returns a new string with the matches replaced by the provided replacement.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ bytes โ€บ how-to-replace-multiple-characters-in-a-string-with-javascript
How to Replace Multiple Characters in a String with JavaScript
September 21, 2023 - Replacing multiple types of characters in a string is a common task in JavaScript, and it's one that can be handled quite elegantly with the replace() method and regular expressions.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String โ€บ replace
String.prototype.replace() - JavaScript - MDN Web Docs
The replace() method of String values returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence ...
Find elsewhere
๐ŸŒ
MUI Stack
muhimasri.com โ€บ blogs โ€บ how-to-replace-multiple-words-and-characters-in-javascript
How to Replace Multiple Words and Characters in JavaScript
December 6, 2021 - Learn how to replace multiple words and characters using regular expressions and replaceAll function in JavaScript
๐ŸŒ
Carl Rippon
carlrippon.com โ€บ replacing-mutliple-instances-of-a-string-inside-string
Replacing multiple instances of a string inside another string in JavaScript
March 17, 2020 - Again, we want to replace all the instances of the word โ€œtheโ€ with โ€œnoโ€. However, this time the two instances of โ€œtheโ€ are in different cases - โ€œTheโ€ and โ€œtheโ€. ... Not quite what we wanted! ... We have extended the regular expression and specified a case insensitive match with i. So, the text variable now contains the value โ€œno cat sat on no matโ€.
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ javascript string replace multiple | example code
JavaScript string replace multiple | Example code
June 28, 2022 - Simple example code replaces multiple occurrences with blank of char in string. <!doctype html> <head> <script> var str = '[T] and [Z] and another [T] and [Z]'; var result = str.replace(/T/g,' ').replace(/Z/g,''); console.log(result); </script> </head> <body> </body> </html> ... Using regex we could also ignore lower/upper-case. var str2 = '(t) or (โ“‰) and (z) or (โ“). But also uppercase (T) or (Z)'; var result2 = str2.replace(/[tโ“‰]/gi,' ').replace(/[zโ“]/gi,''); console.log(result2);
Top answer
1 of 16
94

You could extend the String object with your own function that does what you need (useful if there's ever missing functionality):

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  for (var i = 0; i < find.length; i++) {
    replaceString = replaceString.replace(find[i], replace[i]);
  }
  return replaceString;
};

For global replace you could use regex:

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  var regex; 
  for (var i = 0; i < find.length; i++) {
    regex = new RegExp(find[i], "g");
    replaceString = replaceString.replace(regex, replace[i]);
  }
  return replaceString;
};

To use the function it'd be similar to your PHP example:

var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];
textarea = textarea.replaceArray(find, replace);
2 of 16
59

Common Mistake

Nearly all answers on this page use cumulative replacement and thus suffer the same flaw where replacement strings are themselves subject to replacement. Here are a couple examples where this pattern fails (h/t @KurokiKaze @derekdreery):

function replaceCumulative(str, find, replace) {
  for (var i = 0; i < find.length; i++)
    str = str.replace(new RegExp(find[i],"g"), replace[i]);
  return str;
};

// Fails in some cases:
console.log( replaceCumulative( "tar pit", ['tar','pit'], ['capitol','house'] ) );
console.log( replaceCumulative( "you & me", ['you','me'], ['me','you'] ) );

Solution

function replaceBulk( str, findArray, replaceArray ){
  var i, regex = [], map = {}; 
  for( i=0; i<findArray.length; i++ ){ 
    regex.push( findArray[i].replace(/([-[\]{}()*+?.\\^$|#,])/g,'\\$1') );
    map[findArray[i]] = replaceArray[i]; 
  }
  regex = regex.join('|');
  str = str.replace( new RegExp( regex, 'g' ), function(matched){
    return map[matched];
  });
  return str;
}

// Test:
console.log( replaceBulk( "tar pit", ['tar','pit'], ['capitol','house'] ) );
console.log( replaceBulk( "you & me", ['you','me'], ['me','you'] ) );

Note:

This is a more compatible variation of @elchininet's solution, which uses map() and Array.indexOf() and thus won't work in IE8 and older.

@elchininet's implementation holds truer to PHP's str_replace(), because it also allows strings as find/replace parameters, and will use the first find array match if there are duplicates (my version will use the last). I didn't accept strings in this implementation because that case is already handled by JS's built-in String.replace().

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ javascript-program-to-replace-multiple-characters-in-a-string
JavaScript - How to Replace Multiple Characters in a String? - GeeksforGeeks
July 23, 2025 - The replaceAll() method can replace all instances of specific characters or strings without the need for a regular expression. ... const s1 = "hello world!"; const s2 = s1.replaceAll("l", "x").replaceAll("o", "y"); console.log(s2); ... This ...
๐ŸŒ
JavaScript in Plain English
javascript.plainenglish.io โ€บ javascript-replace-multiple-substrings-8e9e9678bca7
How To Replace Multiple Substrings With Data From an Object in JavaScript | by Louis | JavaScript in Plain English
September 3, 2021 - What we are aiming for, is hydrating a string template with object values. Here is, how we do it. The trick is combining regex with the string.replace function. First, we need to build our regular expression. In many cases, we just pass some regex into theโ€ฆ ... New JavaScript and Web Development content every day.
๐ŸŒ
IncludeHelp
includehelp.com โ€บ code-snippets โ€บ replace-multiple-characters-in-one-replace-call-using-javascript.aspx
Replace multiple characters in one replace call using JavaScript
July 24, 2022 - This can be one way of replacing multiple characters using multiple replace() methods. But let's talk about doing this task by just using the single replace() method. When only a single replace() method has to be used then regular expression comes into consideration. In place of the oldVal a regular expression is declared and in place of the newVal a new character is mentioned. ... // using single replace: let String = 'Replace^ Multiple$ Characters Using_ Replace$ Method.'; newString = String.replace(/\$|_|\^/gi, ''); console.log('Original String: ', String); console.log('New String: ', newString);
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript-program-to-replace-multiple-characters-in-a-string
JavaScript โ€“ How to Replace Multiple Characters in a String? | GeeksforGeeks
November 26, 2024 - The replace() with regular expression and object mapping methods are the most efficient for replacing multiple characters. ... In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings ...
๐ŸŒ
Coder's Block
codersblock.com โ€บ blog โ€บ javascript-string-replace-magic
JavaScript String Replace Magic - Will Boyd / Coder's Block
The most obvious way to do string replacement is by passing 2 strings to replace(), the string to find and the string to replace it with. var str = 'Needs more salt!'; str.replace('salt', 'pepper'); // "Needs more pepper!" replace() does not ...
๐ŸŒ
RSWP Themes
rswpthemes.com โ€บ home โ€บ javascript tutorial โ€บ how to replace multiple characters in a string in javascript
How to Replace Multiple Characters in a String in JavaScript
January 14, 2024 - In this article, youโ€™ll learn how to replace multiple characters in a string using JavaScript. By utilizing the replace() method and regular expressions, you can easily replace specific characters within a string.
Top answer
1 of 1
1

You can do this by using a regular expression with the g flag with replace, passing a callback function as the replacement; the function then picks the appropriate replacement based on what matched.

For instance:

let searches = ["gone", "go", "run"];
let s = "go went gone-go";
const lookup = {
    "go": "(go)",
    "gone": "[gone]",
};
let rex = new RegExp(searches.map(escapeRegex).join("|"), "g");
s = s.replace(rex, match => lookup[match]);
console.log(s);

...where escapeRegex escapes any charactesr in the search strings that have special meaning in regular expressions; see this question's answers for possible implementations.

Live Example:

function escapeRegex(string) {
    return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

let searches = ["gone", "go", "run"];
let s = "go went gone-go";
const lookup = {
    "go": "(go)",
    "gone": "[gone]",
};
let rex = new RegExp(searches.map(escapeRegex).join("|"), "g");
s = s.replace(rex, match => lookup[match]);
console.log(s); // "(go) went [gone]-(go)"

Note: The order of the strings in the searches array matters. If you put "go" before "gone", it'll match first:

function escapeRegex(string) {
    return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

let searches = ["go", "gone", "run"];
// Note โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’^
let s = "go went gone-go";
const lookup = {
    "go": "(go)",
    "gone": "[gone]",
};
let rex = new RegExp(searches.map(escapeRegex).join("|"), "g");
s = s.replace(rex, match => lookup[match]);
console.log(s); // "(go) went (go)ne-(go)"

If you always want the longest one to have the highest precedence, and you can't control the contents of the input array, you could sort it prior to using it:

function escapeRegex(string) {
    return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

let searches = ["go", "gone", "run"];
// Note โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’^
let s = "go went gone-go";
const lookup = {
    "go": "(go)",
    "gone": "[gone]",
};
let rex = new RegExp(
    searches.sort((a, b) => b.length - a.length)
      .map(escapeRegex)
      .join("|"),
    "g"
);
s = s.replace(rex, match => lookup[match]);
console.log(s); // "(go) went [gone]-(go)"