js string replace multiple code example

Example 1: replace many chracters js

// You can use regex to do it in only one replace
// Using the or: |
var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "this is a test"
// Or using the character class 
str.replace(/[#_]/g,''); // result: "this is a test"

Example 2: multiple replace

var str = '[T] and [Z] but not [T] and [Z]';
var result = str.replace('T',' ').replace('Z','');
console.log(result);

Example 3: jquery replace multiple words

// jQuery search and replace space in 10 digit phone number with dots (.)
(".some-class").each(function() {
            var text = $(this).html();
  // Start search at "Phone: " then 3 digits space 3 digits space 4 digits
  // "Phone: 901 123 4567" -> "Phone: 901.123.4567"
            text = text.replace(/Phone: (\d{3}) (\d{3}) (\d{4})/, "Phone: $1.$2.$3");
            $(this).html(text);
        });