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.

Approach 1: Using String.replace()

In this approach, we are Using String.replace() with a regular expression allows you to find and replace specific words or patterns within a string efficiently, enabling global replacements for all occurrences of the target.

Syntax:

function replaceWord(val1, val2, val3) {
let regex = new RegExp(val2, 'g');
return val1.replace(regex, val3);
};

Example: In this example, The replaceWord function uses a regular expression to replace all occurrences of ‘gfg’ with ‘w3wiki’ in the input text, demonstrating word replacement.

Javascript
function replaceWord(val1, val2, val3) {
    let regex = new RegExp(val2, 'g');
    return val1.replace(regex, val3);
}

let inputText = 
    "gfg is a computer science portal.";
let result = 
    replaceWord(inputText, 'gfg', 'w3wiki');
console.log(result);

Output
w3wiki is a computer science portal.

Approach 2: String.split() and Array.join() methods

In this approach, Using String.split() to split a string into words, mapping and replacing specific words, and finally using Array.join() to rejoin the modified words into a new string efficiently.

Syntax:

let words = str1.split(/\s+|\W+/);

Example: In this example, we split the string into words while removing punctuation, compare each word case-insensitively, and replace occurrences of ‘gfg’ with ‘w3wiki’, then rejoin the modified words.

Javascript
let str1 = "gfg, a Computer science Portal.";
let word1 = 'gfg';
let changeWord = 'w3wiki';

// Split the string into words and remove punctuation
let words = str1.split(/\s+|\W+/);

let replacedWords = words.map((word) =>
    (word.toLowerCase() === word1.toLowerCase() 
    ? changeWord : word));

let result = replacedWords.join(' ');

console.log(result);

Output
w3wiki a Computer science Portal 

Approach 3: Using Word Boundary \b in Regular Expression

This method constructs a regular expression with word boundary `\b`, ensuring exact word matches. It replaces all occurrences of the target word with the new word, preserving word boundaries. This prevents unintended replacements within larger words.

Example:

JavaScript
function replaceWords(text, oldWord, newWord) {
    const regex = new RegExp('\\b' + oldWord + '\\b', 'g');
    return text.replace(regex, newWord);
}


console.log(replaceWords("This is a test string", "test", "example")); // "This is a example string"

Output
This is a example string

Approach 4: Using a Map Object for Replacement

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.

JavaScript
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!