Ayro
Ayro

Reputation: 473

Replace Multiple String at Once With Regex in Javascript

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.

Upvotes: 9

Views: 15821

Answers (3)

Naresh Kumar
Naresh Kumar

Reputation: 1061

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

Upvotes: 0

VisioN
VisioN

Reputation: 145368

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.

Upvotes: 5

Just code
Just code

Reputation: 13791

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

Upvotes: 13

Related Questions