Replace multiple characters in one replace call
If you want to replace multiple characters you can call the String.prototype.replace()
with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.
For example, if you want a
replaced with x
, b
with y
, and c
with z
, you can do something like this:
const chars = {'a':'x','b':'y','c':'z'};
let s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);
Output: 234xyz567yyyyxz
Use the OR operator (|
):
var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "this is a test"
You could also use a character class:
str.replace(/[#_]/g,'');
Fiddle
If you want to replace the hash with one thing and the underscore with another, then you will just have to chain. However, you could add 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';
Why not chain, though? I see nothing wrong with that.