How to use Map for Replacement In Javascript
In this approach, we utilize a map to specify the characters to be replaced and their corresponding replacements. We then iterate through the string, replacing each character according to the map. If a character is not found in the map, it remains unchanged.
Example: This demonstrates how we can replace multiple characters in a string using a map for replacement.
// Original String
let str = 'JavaScript is awesome';
// Map of characters to be replaced
const replaceMap = {
'a': '4',
'e': '3',
's': '$',
'o': '0'
};
// Function to replace characters using map
function replaceWithMap(str, replaceMap) {
return str.split('').map(char => replaceMap[char] || char).join('');
}
// Replacing characters using map
let newString = replaceWithMap(str, replaceMap);
// Printing the result
console.log(newString);
Output
J4v4Script i$ 4w3$0m3
JavaScript Program to Replace Multiple Characters in a String
We are going to learn how we can replace Multiple Characters in a String. We have to replace multiple characters in a string using the inbuilt function or any other method.
Table of Content
- Using replace() method
- Using replaceAll() method
- Using split() and join()
- Using regular expression
- Using reduce()
- Using Map() Method
Contact Us