Replace Multiple String at Once With Regex in Javascript

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];
});

Check fiddle


One possible solution:

var a = ['a','o','e'],
    b = ['1','2','3'];

'stackoverflow'.replace(new RegExp(a.join('|'), 'g'), function(c) {
    return b[a.indexOf(c)];
});

As per the comment from @Stephen M. Harris, here is another more fool-proof solution:

'stackoverflow'.replace(new RegExp(a.map(function(x) {
    return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}).join('|'), 'g'), function(c) {
    return b[a.indexOf(c)];
});

N.B.: Check the browser compatibility for indexOf method and use polyfill if required.