Let's say I have a string like "abcabcabc"
and I want the positions of 'a's and 'b's swapped so that I end up with "bacbacbac"
. What is the most elegant solution for this? (For the sake of this question I hereby define 'elegant' as fast and readable.)
I came up with
"abcabcabc".replace( /[ab]/g, function( c ){ return { 'a': 'b', 'b': 'a' }[ c ] } )
Which I neither regard fast nor readable. But now I wonder if there is a better way of doing it?
EDIT: The characters can be at any position. So the answer should hold for "xyza123buvwa456" (would be then "xyzb123auvwb456", too.
EDIT2: "swap" seems to be the wrong word. Replace all of a with b and all of b with a while both are single characters.
I throw in a couple of other ones:
"abcabcabc".replace( 'a', '_' ).replace( 'b','a' ).replace( '_', 'b' )
"abcabcabc".replace( /[ab]/g, function( c ){ return "ba".charAt( c.charCodeAt()-'a'.charCodeAt() ); } )
"abcabcabc".replace( /[ab]/g, function( c ){ return "ab".charAt( "ba".indexOf( c ) ) } )
I ended up using a modified version of Mark C.'s Answer:
"abcabcabc".replace( /[ab]/g, c => c == 'a' ? 'b' : 'a' )