Replace Specific Words in a String Using Regular Expressions in JavaScript
Last Updated :
16 Jul, 2024
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:
We will explore all the above methods along with their basic implementation with the help of examples.
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 ‘GeeksforGeeks’ 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', 'GeeksforGeeks');
console.log(result);
OutputGeeksforGeeks is a computer science portal.
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 ‘GeeksforGeeks’, then rejoin the modified words.
JavaScript
let str1 = "gfg, a Computer science Portal.";
let word1 = 'gfg';
let changeWord = 'GeeksforGeeks';
// 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);
OutputGeeksforGeeks 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"
OutputThis 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 'GeeksforGeeks'. gfg is great!";
const replacements = new Map([
['gfg', 'GeeksforGeeks'],
['great', 'awesome']
]);
const replacedText = replaceWordsWithMap(inputText, replacements);
console.log(replacedText);
OutputReplace all occurrences of 'GeeksforGeeks' with 'GeeksforGeeks'. GeeksforGeeks is awesome!
Approach 5: Using a Callback Function in String.replace()
In this approach, we use a callback function within String.replace() to customize the replacement logic based on more complex criteria. This method provides flexibility to handle context-sensitive replacements or incorporate additional logic during the replacement process.
Example: In this example, we use a callback function to replace all occurrences of the target word ‘gfg’ with ‘GeeksforGeeks’, but only if the word is not part of a larger word. The callback checks if the matched word is exactly ‘gfg’ and performs the replacement accordingly.
JavaScript
function replaceWithCallback(str, pattern, callback) {
let regex = new RegExp(pattern, 'g');
return str.replace(regex, callback);
}
let inputText = "gfg is a computer science portal. Visit gfg!";
let pattern = '\\b(gfg)\\b';
let result = replaceWithCallback(inputText, pattern, (match) => {
if (match === 'gfg') {
return 'GeeksforGeeks';
}
return match;
});
console.log(result);
OutputGeeksforGeeks is a computer science portal. Visit GeeksforGeeks!
Similar Reads
Reverse Words Starting with Particular Characters using JavaScript
We need to create a JavaScript function that reverses the order of all words in a given sentence that begins with a specific character. JavaScript allows us to reverse the words in a sentence that start with specific letters. Examples: Input: str= "I like to cook delicious meals every day"Character
4 min read
Find Number of Consonants in a String using JavaScript
In JavaScript, counting the number of consonants in a string can be achieved through various approaches. Consonants are the letters excluding vowels (a, e, i, o, u). Examples: Input : abcdeOutput : 3There are three consonants b, c and d.Input : geeksforgeeks portalOutput : 12Table of Content Using I
2 min read
JavaScript Program to Find all Strings that Match Specific Pattern in a Dictionary
Finding all strings in a dictionary that match a specific pattern in JavaScript involves searching for words that follow a particular structure or format within a given dictionary. The pattern can include placeholders for characters, allowing flexibility in the search. In this article, we will explo
7 min read
JavaScript Program to Count the Occurrences of a Specific Character in a String
In this article, we will see how to count the frequency of a specific character in a string with JavaScript. Counting the frequency of a specific character in a string is a common task in JavaScript. Example: Input : S = âgeeksforgeeksâ and c = âeâOutput : 4Explanation: âeâ appears four times in str
3 min read
Remove all occurrences of a character in a string using JavaScript
These are the following ways to remove all occurrence of a character from a given string: 1. Using Regular ExpressionUsing a regular expression, we create a pattern to match all occurrences of a specific character in a string and replace them with an empty string, effectively removing that character
2 min read
Split a Sentence into Fixed-Length Blocks without Breaking Words in JavaScript
Given a sentence, our task is to split it into blocks of a fixed length without breaking words using JavaScript. Example: Input: Sentence= "This is a sample sentence to demonstrate splitting into blocks without breaking words.", blocksize = 15Output:Blocks: [ 'This is a', 'sample sentence ', 'to dem
3 min read
JavaScript Program to Swap Characters in a String
In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings in JavaScript, and perform character swaps efficiently. There are different approaches for swapping characters in a String in JavaScript: Table of Content Using Array ManipulationUsin
6 min read
JavaScript Program to Remove Vowels from a String
The task is to write a JavaScript program that takes a string as input and returns the same string with all vowels removed. This means any occurrence of 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase) should be eliminated from the string. Given a string, remove the vowels from the string and
2 min read
JavaScript Program for Converting given Time to Words
This article will show you how to convert the given time into words in JavaScript. The given time will be in 12-hour format (hh: mm), where 0 < hh < 12, and 0 <= mm < 60. Examples: Input : hh = 6, mm = 20Output : Six Hour, Twenty MinutesInput : hh = 8, mm = 24Output : Eight Hour, Twenty
2 min read
JavaScript Program to Calculate the Frequency of Each Word in the Given String
Given a string, our task is to calculate the Frequency of Each Word in the Given String using JavaScript. Example:Input:"geeks for geeks is for geeks"Output:"geeks": 3 , "for": 2 , "is": 1 Below are the approaches for calculating the Frequency of Each Word in the Given String using JavaScript: Table
3 min read