Replace Multiple Words with K in JavaScript
Last Updated :
19 Feb, 2024
Sometimes, while working with Javascript strings, we may face a problem in which we have to perform a replacement of multiple words with a single word. This can have applications in many domains like day-day programming and school programming.
These are the following approaches:
Using join() and split() methods
The combination of the join() and split() functions can be used to perform this task. In this, we split the string into words, check and replace the list words using join and list.
Example: This example shows the use of the join() and split() methods to replace words.
JavaScript
// Initialize string
let test_str =
'Geeksforgeeks is best for geeks and CS';
// Print original string
console.log("The original string is : " + test_str);
// Initialize word list
let word_list = ["best", 'CS', 'for'];
// Initialize replace word
let repl_wrd = 'gfg';
// Replace multiple words with K
// Using split(), map() and includes()
let res = test_str.split(' ').map(word =>
word_list.includes(word) ? repl_wrd : word).join(' ');
// Print result
console.log("String after multiple replace : " + res);
OutputThe original string is : Geeksforgeeks is best for geeks and CS
String after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg
Time Complexity: O(n)
Space Complexity: O(n)
Using Regex and join() method
Now we will use combination of regex and join() method to get the desired result. In JavaScript, the join() method and regular expressions (regex) are both valuable tools for working with text, but they serve distinct purposes. The join() method combines elements of an array or iterable into a single string, using a specified separator between each element. Regex are powerful patterns used to search, extract, and manipulate text based on defined patterns.
Example: This example shows the use of regular expression to replace the word.
JavaScript
// Initialize string
let test_str =
'Geeksforgeeks is best for geeks and CS';
// Print original string
console.log("The original string is : " + test_str);
// Initialize word list
let word_list = ["best", 'CS', 'for'];
// Initialize replace word
let repl_wrd = 'gfg';
// Create a regular expression pattern from word_list
let pattern = new RegExp(word_list.join('|'),
'g');
// Replace multiple words with K
let res = test_str.replace(pattern, repl_wrd);
// Print the result
console.log("String after multiple replace : "
+ res);
OutputThe original string is : Geeksforgeeks is best for geeks and CS
String after multiple replace : Geeksgfggeeks is gfg gfg geeks and gfg
Time Complexity: O(n)
Space Complexity: O(n)
Using for Loop and replace() method
Now we will use for loop and replace() method to get the required output. The replace() method will be used to search a string for a value. It usually returns a new string with the value(s) replaced. So we will run the for loop till the size of word_list.
Example: This example shows the use of loop and replace() method to replace the word.
JavaScript
// Initialize string
let test_str = `Geeksforgeeks is best
for computer science and IT`;
// Print original string
console.log("The original string is : " + test_str);
// Initialize word list
let word_list = ["best", 'IT', 'for'];
// Initialize replace word
let repl_wrd = 'gfg';
// Replace multiple words with K
for (let i = 0; i < word_list.length; i++) {
test_str = test_str.replace(new RegExp(word_list[i],
'g'), repl_wrd);
}
// Print the result
console.log("String after multiple replace : " + test_str);
OutputThe original string is : Geeksforgeeks is best
for computer science and IT
String after multiple replace : Geeksgfggeeks is gfg
gfg computer science and gfg
Time Complexity: O(n*m) where n is the length of the input string and m is the number of words in the word_list.
Space Complexity: The space complexity is O(n), where n is the length of the input string test_str.
Using map() method
Another method to solve the problem is by splitting the string into an array of words, then using the map() method to iterate over each word and replace it if it exists in the word_list. Finally, we join the modified array back into a string.
Example: This example shows the use of map() method to replace the word.
JavaScript
// Initialize string
let test_str = `Geeksforgeeks is best
for computer science and IT`;
// Print original string
console.log("The original string is : "
+ test_str);
// Initialize word list
let word_list = ["best", 'CS', 'for'];
// Initialize replace word
let repl_wrd = 'gfg';
// Replace multiple words with K
let res = test_str.split(' ').map(word => {
if (word_list.includes(word)) {
return repl_wrd;
}
return word;
}).join(' ');
// Print the result
console.log("String after multiple replace : "
+ res);
OutputThe original string is : Geeksforgeeks is best
for computer science and IT
String after multiple replace : Geeksforgeeks is gfg
for computer science and IT
Time Complexity: O(n)
Space Complexity: O(n)
Similar Reads
Create a string with multiple spaces in JavaScript
We have a string with extra spaces and if we want to display it in the browser then extra spaces will not be displayed. Adding the number of spaces to the string can be done in the following ways. In this article, we are going to learn how to Create a string with multiple spaces in JavaScript. Below
3 min read
Replace multiple strings with multiple other strings in JavaScript
In this article, we are given a Sentence having multiple strings. The task is to replace multiple strings with new strings simultaneously instead of doing it one by one, using JavaScript. Below are a few methods to understand: Table of Content Using JavaScript replace() method Using the JavaScript s
2 min read
JavaScript string replace() Method
JavaScript replace() method is used for manipulating strings. It allows you to search for a specific part of a string, called a substring, and then replace it with another substring. What's great is that this method doesn't alter the original string, making it ideal for tasks where you want to maint
5 min read
JavaScript replaceAt() Method
The replaceAt() method is useful for removing the character at a given place. Unfortunately, the replaceAt() method is not a built-in method in JavaScript. It would need to be defined by the user in order to use it. One possible implementation of a replaceAt() function could take a string and two in
2 min read
Wildcard Pattern Matching in JavaScript
In this article, we will see Pattern matching with wildcards which is an encountered problem, in the field of computer science and string manipulation. The objective is to determine whether a given wildcard pattern matches a string or not. In this article, we will discuss the step-by-step algorithm
4 min read
JavaScript - How to Replace Multiple Spaces with a Single Space?
Here are the various methods to replace multiple spaces with a single space in JavaScript. 1. Using replace() Method with Regular Expression (Most Common)The replace() method combined with a regular expression is the most efficient way to replace multiple spaces with a single space. [GFGTABS] JavaSc
2 min read
JavaScript String replaceAll() Method
The replaceAll() method in JavaScript is used to replace all occurrences of a specified substring or pattern with a new substring. The replaceAll() method does not change the original string. JavaScript's replaceAll() method used for replacing all instances of a specified substring or pattern within
3 min read
JavaScript Replace() Method
The replace() method in JavaScript is used to search a string for a value or any expression and replace it with the new value provided in the parameters. The original string is not changed by this method. Syntax: string.replace(searchVal,newVal) Parameter: This method accepts two parameters. searchV
2 min read
How to replace plain URL with link using JavaScript ?
Given a plane URL, the task is to replace the plain URLs with the links. This problem can be solved with the help of Regular Expressions. Approach: Using RegExp and replace() MethodRegExp - This looks for the URL in the provided text.This RegExp parses the URL and puts the address to the $1 variable
2 min read
JavaScript Reverse a string in place
JavaScript reverses a string in place refers to the process of flipping the order of characters within the string without using additional memory. It involves iterating through the string and swapping characters from both ends until reaching the middle. Reverse a string in place ExampleUsing the Jav
5 min read