Elegant char set to replace in javascript / jQuery

I have a JS string that requires replacing multiple characters.

For example, for an input line:

s = 'ABAC' 

I would like to replace all B with C and vice versa. However, doing a standard regular expression replacement is not good enough, since replace() should not be executed in lockstep, but only in one pass per line.

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

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

(The solution should work for any arbitrary char replacement)

+4
source share
3 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 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); /* ACABABBCA */ 

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.

+9
source

You need the translate function; see this question for an example implementation.

0
source

There may be more neat ways to do this, but I usually do something as simple as this ....

 s.replace(/B/g, '##_B_##').replace(/C/g, 'B').replace(/##_B_##/g, 'C'); 

In principle, make B unique until you replace C with B so that the original Bs can still be identified.

0
source

Source: https://habr.com/ru/post/1399411/


All Articles