How to Replace Multiple Strings in JavaScript
![How to Replace Multiple Strings in JavaScript](https://javascripts.com/wp-content/uploads/2023/06/qzys2w0iij7ofbz3hmqi-1200x675.png)
JavaScript, a key pillar in today’s digital world, is more than just a tool to make websites dynamic. It allows us to manipulate data in various ways, including replacing multiple strings – a task that can often pop up in coding scenarios.
You might think replacing multiple strings can get complicated, but it doesn’t have to be. Let’s dive into some easy to follow methods together. By the end, you’ll be able to handle this task with ease and confidence.
In this post, we will be looking at the following 3 ways to replace multiple strings in JavaScript:
- By using replace() with a regular expression
- By using split() and join() methods
- By using a custom function with a loop and String.prototype.replace()
Let’s explore each…
#1 – By using replace() with a regular expression
This process involves creating a regular expression to match multiple strings and using the replace() method in JavaScript to replace these strings globally. It’s easier to understand this with an example:
var str = "I like oranges, apples, and bananas";
var newStr = str.replace(/oranges|apples|bananas/g, "fruits");
How it works
The replace() method in JavaScript is used to replace certain characters or words in a string with specified characters or words. In this case, we are combining it with a regular expression to detect and replace multiple words.
- The variable ‘str’ is our original string.
- ‘/oranges|apples|bananas/g’ is our regular expression. The pipe ‘|’ acts as an OR operator, so it will match any of the words ‘oranges’, ‘apples’, or ‘bananas’. The ‘g’ at the end makes the replacement global, so it will replace all instances of these words, not just the first one.
- The second parameter to the replace() method is the string that will replace the matched words, in this case, “fruits”.
- So, the sentence “I like oranges, apples, and bananas” becomes “I like fruits, fruits, and fruits”.
#2 – By using split() and join() methods
In JavaScript, you can replace multiple strings by using the split() method to separate the string at the points where the target substring occurs, and then using join() to glue the sections back together, replacing the target substring with a new one. For example, if you want to replace all occurrences of ‘cat’ with ‘dog’ in a string, you would first split the string at each ‘cat’, then join the resulting array with ‘dog’.
let str = 'I love my cat. My cat is very cute.';
let newStr = str.split('cat').join('dog');
How it works
The function first splits the original string into an array where the ‘cat’ occurs, then joins the array back together, replacing ‘cat’ with ‘dog’.
- The
split('cat')
method splits the input string into an array of substrings at each occurrence of the word ‘cat’, and returns the new array. - The resulting array for our example would be [“I love my “, “. My “, ” is very cute.”]. Notice how the ‘cat’ is no longer present.
- The
join('dog')
method then joins the elements of the array into a string, inserting ‘dog’ between each element. - The final string is “I love my dog. My dog is very cute.”. The ‘cat’ has been replaced by ‘dog’.
#3 – By using a custom function with a loop and String.prototype.replace()
This approach works by using a custom function that iterates over a list of words to be replaced in a given string using String.prototype.replace(). An example would be replacing all instances of “good” and “bad” in a text with “great” and “poor” respectively.
function replaceStrings(text, toReplace, replaceWith) {
for (let i = 0; i < toReplace.length; i++) {
text = text.replace(new RegExp(toReplace[i], "g"), replaceWith[i]);
}
return text;
}
let text = "This is a good day, but also a bad day.";
let toReplace = ["good", "bad"];
let replaceWith = ["great", "poor"];
console.log(replaceStrings(text, toReplace, replaceWith));
// Output: "This is a great day, but also a poor day."
How it works
This function takes three parameters: the original text, an array of the words to be replaced, and an array of the replacement words. It then uses a for loop to go through each word that needs to be replaced, and uses the JavaScript String.prototype.replace() method to replace each instance of that word with the corresponding replacement. The function finally returns the modified text.
- Step 1: The function 'replaceStrings' is defined with three parameters: 'text', 'toReplace', and 'replaceWith'.
- Step 2: A 'for' loop is run over the 'toReplace' array.
- Step 3: Inside the loop, 'text.replace()' is called for each word in the 'toReplace' array, replacing it with the corresponding word from the 'replaceWith' array. The 'g' flag in the RegExp constructor ensures all instances of the word are replaced, not just the first one.
- Step 4: After all replacements are made, the modified text is returned.
- Step 5: The function 'replaceStrings' is then called with the original text and the arrays of words to replace and replacement words, and the output is logged to the console.
Related:
- How to Remove a String from Another String in JavaScript
- How to Perform Factorialization in JavaScript
- How to Parse Strings in JavaScript
In conclusion, replacing multiple strings in JavaScript is a task that can be accomplished with a few lines of code. With the help of regular expressions and the replace() method, we can easily handle multiple string replacements in our data.
Remember, practice is key in mastering these methods. Don't be afraid to experiment with different strings and scenarios. You'll be a JavaScript string replacement expert before you know it!