Home > Web Front-end > JS Tutorial > How to Perform Multiple String Replacements in JavaScript?

How to Perform Multiple String Replacements in JavaScript?

Barbara Streisand
Release: 2024-11-29 09:44:10
Original
643 people have browsed it

How to Perform Multiple String Replacements in JavaScript?

Multiple String Replacement in JavaScript

String replacement is a common task in programming. In JavaScript, the replace() method allows you to replace a single match of a specified string with a new one. However, what if you want to replace multiple strings with multiple other strings at the same time?

Consider the following example:

var str = "I have a cat, a dog, and a goat.";

// Attempt to replace multiple strings with incorrect results
str = str.replace(/cat/gi, "dog");
str = str.replace(/dog/gi, "goat");
str = str.replace(/goat/gi, "cat");

// Output: "I have a cat, a cat, and a cat"
Copy after login

As you can see, this does not produce the desired result of "I have a dog, a goat, and a cat." Instead, it incorrectly substitutes every instance of "cat" with "dog," and so on.

Specific Solution

To achieve the desired result, you can use a function to handle each replacement:

var str = "I have a cat, a dog, and a goat.";
var mapObj = {
   cat:"dog",
   dog:"goat",
   goat:"cat"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
  return mapObj[matched];
});

// Output: "I have a dog, a goat, and a cat"
Copy after login

In this approach, we create a map object (mapObj) that defines the key-value pairs of strings to be replaced. Then, we use a regular expression that matches any of these strings and replaces them with the corresponding value from the map object.

Generalizing the Solution

To generalize this approach, you can dynamically create the regular expression and update the map object as needed:

var mapObj = {cat:"dog",dog:"goat",goat:"cat"};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi"); 
str = str.replace(re, function(matched){
  return mapObj[matched];
});
Copy after login

This approach allows you to add or remove replacement pairs without modifying the regular expression itself.

Reusable Function

To further abstract the process, you can create a reusable function:

function replaceAll(str,mapObj){
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");

    return str.replace(re, function(matched){
        return mapObj[matched.toLowerCase()];
    });
}
Copy after login

You can then use this function to replace multiple strings with multiple other strings in any given string.

The above is the detailed content of How to Perform Multiple String Replacements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template