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.
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
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.
Contact Us