9

I tried this : Replace multiple strings at once And this : javascript replace globally with array how ever they are not working.

Can I do similar to this (its PHP):

$a = array('a','o','e');
$b = array('1','2','3');
str_replace($a,$b,'stackoverflow');

This result will be :

st1ck2v3rfl2w

I want to use regex at the same time. How can I do that ? Thank you.

Community
  • 1
  • 1
Ayro
  • 473
  • 2
  • 5
  • 12
  • **You can find a replace a string using delimiters ** [click here](https://stackoverflow.com/a/58862890/8427094) – Naresh Kumar Nov 14 '19 at 17:50
  • 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:20

3 Answers3

13
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

Just code
  • 13,553
  • 10
  • 51
  • 93
5

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.

Community
  • 1
  • 1
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • This can break if the find strings contain any special regex chars. Here's an improved version (and also cross-browser w/o polyfills) http://stackoverflow.com/a/37949642/445295 – Stephen M. Harris Jun 21 '16 at 16:29
  • @StephenM.Harris I have added another variant, that will take care of the edge cases with special regex characters. – VisioN Jun 21 '16 at 18:09
0

You can use delimiters and replace a part of the string

var obj = {
  'firstname': 'John',
  'lastname': 'Doe'
}

var text = "My firstname is {firstname} and my lastname is {lastname}"

console.log(mutliStringReplace(obj,text))

function mutliStringReplace(object, string) {
      var val = string
      var entries = Object.entries(object);
      entries.filter((para)=> {
          var find = '{' + para[0] + '}'
          var regExp = new RegExp(find,'g')
       val = val.replace(regExp, para[1])
    })
  return val;
}
Naresh Kumar
  • 871
  • 7
  • 8