JavaScript string replace multiple | Example code

  • by

Using the chained replace() method will work to string replace multiple in JavaScript. But a simple replace only replaces the first occurrence. To replace all, regex still comes in handy. By making use of the global g flag.

 string.replace(/str/g,' ').replace(/str/g,'');

JavaScript string replace multiple example

Simple example code replaces multiple occurrences with blank of char in string.

<!doctype html>
  <head>

    <script>
      var str = '[T] and [Z] and another [T] and [Z]';
      var result = str.replace(/T/g,' ').replace(/Z/g,'');
      console.log(result);

    </script>
  </head>
  <body>

  </body>
  </html>

Output:

JavaScript string replace multiple

Using regex we could also ignore lower/upper-case.

var str2 = '(t) or (Ⓣ) and (z) or (Ⓩ). But also uppercase (T) or (Z)';
var result2 = str2.replace(/[tⓉ]/gi,' ').replace(/[zⓏ]/gi,'');
console.log(result2);

Source: stackoverflow.com

Replace multiple characters in one replace call

Use the OR operator (|):

var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "this is a test"

How to JS Replace multiple strings with multiple other strings?

Answer: Use a function to replace each one.

    <script>
      var str = "I have an cat, an dog, and a goat.";
      var mapObj = {
        cat:"Apple",
       dog:"Orange",
       goat:"Cherry"
     };
     str = str.replace(/cat|dog|goat/gi, function(matched){
      return mapObj[matched];
    });
     console.log(str);

   </script>

Output: I have an Apple, an Orange, and a Cherry.

Do comment if you have any doubts or suggestions on this JS replace code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.