2 ways to replace multiple strings:
- Using String replace() method
- Using String replaceAll() method
Method 1: String replace() method
You can use the string.replace() method to replace multiple strings with other strings.
Visual Representation
let str = "Netflix has StrangerThings, BlackMirror, and HouseOfCards";
let mapObj = {
StrangerThings:"Millie Bobby Brown",
BlackMirror:"Anthony Mackie",
HouseOfCards:"Kevin Spacey"
};
replacedString = str.replace(/StrangerThings|BlackMirror|HouseOfCards/gi, function(matched){
return mapObj[matched];
});
console.log(replacedString);
Output
Netflix has Millie Bobby Brown, Anthony Mackie, and Kevin Spacey
To make a reusable code, use the following code snippet.
function replaceAll(str, mapObj){
let result = new RegExp(Object.keys(mapObj).join("|"),"gi");
return str.replace(result, function(matched){
return mapObj[matched];
});
}
let str = "Netflix has StrangerThings, BlackMirror, and HouseOfCards";
let mapObj = {
StrangerThings:"Millie Bobby Brown",
BlackMirror:"Anthony Mackie",
HouseOfCards:"Kevin Spacey"
};
replacedString = replaceAll(str, mapObj);
console.log(replacedString);
So in the above code, you could pass the str and mapobj to a function, which would return the transformed string. It will give us the same output.
Method 2: String replaceAll() method
The string.replaceAll() method returns a new string with all matches of a pattern replaced by a replacement.
Visual Representation
let str = 'Millie@Bobby_Brown';
let output = str
.replaceAll('@', '-')
.replaceAll('_', '-');
console.log(output);
Output
Millie-Bobby-Brown