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.

asked Dec 23, 2013 at 12:33
2

3 Answers 3

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

answered Dec 23, 2013 at 12:34

Comments

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.

answered Dec 23, 2013 at 12:35

2 Comments

This can break if the find strings contain any special regex chars. Here's an improved version (and also cross-browser w/o polyfills) stackoverflow.com/a/37949642/445295
@StephenM.Harris I have added another variant, that will take care of the edge cases with special regex characters.
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;
}

answered Nov 14, 2019 at 17:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.