How to usea Map Object for Replacement in Javascript
In this approach, we can use a map object to store the words we want to replace and their corresponding replacements. We iterate through the map object and use regular expressions to replace all occurrences of each word with its replacement in the string.
function replaceWordsWithMap(str, replacements) {
for (const [word, replacement] of replacements.entries()) {
const regex = new RegExp(`\\b${word}\\b`, 'gi');
str = str.replace(regex, replacement);
}
return str;
}
// Example usage:
const inputText = "Replace all occurrences of 'gfg' with 'w3wiki'. gfg is great!";
const replacements = new Map([
['gfg', 'w3wiki'],
['great', 'awesome']
]);
const replacedText = replaceWordsWithMap(inputText, replacements);
console.log(replacedText);
Output
Replace all occurrences of 'w3wiki' with 'w3wiki'. w3wiki is awesome!
JavaScript Program Replace Specific Words with Another Word in a String using Regular Expressions
In this article, we are going to learn about replacing specific words with another word in a string using regular expressions. Replacing specific words with another word in a string using regular expressions in JavaScript means searching for all occurrences of a particular word or pattern within the text and substituting them with a different word or phrase, considering possible variations and multiple instances.
There are several methods that can be used to replace specific words with another word in a string using regular expressions in JavaScript, which are listed below:
Table of Content
- Approach 1: Using String.replace()
- Approach 2: String.split() and Array.join() methods
- Approach 3: Using Word Boundary \b in Regular Expression
- Approach 4: Using a Map Object for Replacement
We will explore all the above methods along with their basic implementation with the help of examples.