Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant multiple char replace in JavaScript/jQuery

I have a JS string that needs several of its chars replaced.

For example, for input string:

s = 'ABAC'

I would want to replace all Bs with Cs and vice versa. However, doing a standard regex replace is not good enough since the replace()s should not occur in lockstep but rather in a single pass on the string.

>>> s.replace(/B/g, 'C').replace(/C/g, 'B')
'ABAB' // not good

Is there an elegant way to do multiple string replace() in a single pass?

(Solution must work for any arbitrary char replacement)

like image 939
Yuval Adam Avatar asked Jan 18 '23 08:01

Yuval Adam


1 Answers

var str = 'ABACACCBA',
    out = str.replace(/[CB]/g, function(c) {
        return {
            "B" : "C",
            "C" : "B"
        }[c];
    });

console.log(out);  /* ACABABBCA */

all you have to do is to define all characters to match and then an object with swapping rules. An alternative can be also done in this way

var str = 'ABACACCBA',
    out = str.replace(/\w/g, function(c) {
        return {
            "B" : "C",
            "C" : "B"
        }[c] || c;
    });

console.log(out);  /* ACABABBCA */

in this example you execute the function for every character matched, but you make a swap only if you defined an entry into the object (otherwise you return the original character).

It's clearly more expensive (so better use the first example) but in this case you avoid to list all characters to match in the regular expression.

like image 120
Fabrizio Calderan Avatar answered Jan 30 '23 18:01

Fabrizio Calderan