How can I replace multiple characters in a string?

Viewed 67806

I want to create a regex with following logic: 1., If string contains T replace it with space 2., If string contains Z remove Z

I wrote two regex already, but I can't combine them:

string.replace(/\T/g,' ') && string.replace(/\Z/g,'');

EDIT: I want the regex code to be shorter

4 Answers

Second Update

I have developed the following function to use in production, perhaps it can help someone else. It's basically a loop of the native's replaceAll Javascript function, it does not make use of regex:

function replaceMultiple(text, characters){
  for (const [i, each] of characters.entries()) {
    const previousChar = Object.keys(each);
    const newChar = Object.values(each);

    text = text.replaceAll(previousChar, newChar);
  }  
  
return text
}

Usage is very simple:


const text = '#Please send_an_information_pack_to_the_following_address:';
const characters = [
    {
    "#":""
    },
   {
    "_":" "
    },
]

const result = replaceMultiple(text, characters);

console.log(result); //'Please send an information pack to the following address:'

Update

You can now use replaceAll natively.

Outdated Answer

Here is another version using String Prototype. Enjoy!

String.prototype.replaceAll = function(obj) {
    let finalString = '';
    let word = this;
    for (let each of word){
        for (const o in obj){
            const value = obj[o];
            if (each == o){
                each = value;
            }
        }
        finalString += each;
    }
    
    return finalString;
};

'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"
Related