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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read