There are the following methods to replace multiple strings with other strings in JavaScript.
- Method 1: Using the string.replace() function
- Method 2: Using the split() and join() functions
Method 1: Using the string.replace() function
You can use the string.replace() method to replace multiple strings with other strings in JavaScript.
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: Using split() and join() functions to replace all spaces
You can use the split() and join() methods to replace all the spaces in the string.
let str = 'Millie Bobby Brown';
let replaced = str.split(' ').join('#');
console.log(replaced)
Output
Millie#Bobby#Brown
One thing to note is that the above solution is slower on large replacement than the reg expression version.
You can use the regex on the above code, like the following.
let str = 'Millie Bobby Brown';
let replaced = str.replace(/\s/g, "#");
console.log(replaced)
That’s it.