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
-
**You can find a replace a string using delimiters ** click hereNaresh Kumar– Naresh Kumar2019年11月14日 17:50:08 +00:00Commented Nov 14, 2019 at 17:50
-
Does this answer your question? Replace multiple strings at onceStephen M. Harris– Stephen M. Harris2020年10月28日 22:20:58 +00:00Commented Oct 28, 2020 at 22:20
3 Answers 3
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];
});
answered Dec 23, 2013 at 12:34
Comments
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
Stephen M. Harris
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
VisioN
@StephenM.Harris I have added another variant, that will take care of the edge cases with special regex characters.
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
lang-js