How to use String.split() and Array.join() Method In Javascript

This method involves using split() to break the string at each target substring and then using join() to reassemble the string with the new substring in place of the target substrings.

Example: In this example, we will replace multiple substrings using split() and join() methods.

JavaScript
let str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab.";
let replacements = {
    "Lenovo": "Dell",
    "Honor": "OnePlus",
    "Samsung": "Lenovo"
};

function replaceMultiple(str, replacements) {
    for (let [oldStr, newStr] of Object.entries(replacements)) {
        str = str.split(oldStr).join(newStr);
    }
    return str;
}

console.log(replaceMultiple(str, replacements));

Output
I have a Dell Laptop, a OnePlus Phone, and a Lenovo Tab.





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 str.replaceAll() method
  • Using Array.reduce() method:

Similar Reads

Using JavaScript replace() method

This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value....

Using the JavaScript str.replaceAll() method

In this example, we will see the use of the JavaScript str.replaceAll() method for replacing multiple strings....

Using Array.reduce() method:

Using Array.reduce() with replaceAll() method, the approach iterates over an array of replacement pairs, applying each replacement to the string sequentially. It uses regular expressions to globally replace occurrences of each old string with its corresponding new string....

Using JavaScript String.split() and Array.join() Method

This method involves using split() to break the string at each target substring and then using join() to reassemble the string with the new substring in place of the target substrings....

Contact Us