Replace Multiple String at Once With Regex in Javascript

Viewed 14608

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.

3 Answers

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

Related