Coder Perfect

Multiple characters can be replaced in a single replace call.

Problem

I have a very easy question, but I’m not sure how to answer it.

Every instance of ‘_’ must be replaced with a space, and every instance of ‘#’ must be replaced with nothing/empty.

var string = ‘#Please send an information package to the following address:’; var string = ‘#Please send an information package to the following address:’; var string =

I’ve tried this:

string.replace(‘#’,”).replace(‘_’, ‘ ‘);

I’m not a big fan of command chains like this. Is there a way to accomplish it in a single?

Asked by Shannon Hochkins

Solution #1

Use the OR (|) operator:

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

A character class could also be used:

str.replace(/[#_]/g,'');

If you want to replace the hash with one thing and the underscore with another, then you will just have to chain. You might, however, include a prototype:

String.prototype.allReplace = function(obj) {
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
    }
    return retStr;
};

console.log('aabbaabbcc'.allReplace({'a': 'h', 'b': 'o'}));
// console.log 'hhoohhoocc';

But why not make a chain? That doesn’t bother me in the least.

Answered by tckmn

Solution #2

You can use String.prototype.replace() to replace several characters, with the replacement parameter being a function that is called for each match. You only require an object that represents the character mapping that will be used in that function.

If you want to replace a with x, b with y, and c with z, for example, you can do something like this:

var chars = {'a':'x','b':'y','c':'z'};
var s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);

Output: 234xyz567yyyyxz

Answered by Voicu

Solution #3

Why dismiss chaining when it’s so cool?

Anyway, here’s another replacement option:

string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})

If match==”#,” the replace will choose “,” if it isn’t.

[Update] You might save your replacement strings in an object for a more generic solution:

var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})

Answered by Christophe

Solution #4

To replace all matches instead of just the first, use the /g (global) flag on the regular expression:

string.replace(/_/g, ' ').replace(/#/g, '')

You can’t really avoid needing two distinct calls to replace one character with one thing and another character with something else. You can abstract it into a function like Doorknob did, but instead of a flat array, I’d have it take an object with old/new as key/value pairs.

Answered by Mark Reed

Solution #5

I’m not sure how much this will help, but I wanted to get rid of the b> and /b> characters from my string.

so I used

mystring.replace('<b>',' ').replace('</b>','');

So, if you only want a small number of characters and don’t want to waste time, this will be handy.

Answered by Hrishikesh Kale

Post is based on https://stackoverflow.com/questions/16576983/replace-multiple-characters-in-one-replace-call