Skip to content

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 examples

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

<!doctype html>

      var str = '[T] and [Z] and another [T] and [Z]';
      var result = str.replace(/T/g,' ').replace(/Z/g,'');




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,'');


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.

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


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. Required fields are marked *