var str = 'ABACACCBA', out = str.replace(/[CB]/g, function(c) { return { "B" : "C", "C" : "B" }[c]; }); console.log(out);
all you have to do is define all the characters to match, and then the object with the swap rules. Similarly, an alternative can be made.
var str = 'ABACACCBA', out = str.replace(/\w/g, function(c) { return { "B" : "C", "C" : "B" }[c] || c; }); console.log(out);
in this example, you execute a function for each associated character, but you only swap if you define an entry in the object (otherwise you return the original character).
This is clearly more expensive (so itβs better to use the first example), but in this case you avoid listing all the characters that should match in the regular expression.
source share