Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  4] [ 1]  / answers: 1 / hits: 18151  / 6 Years ago, thu, february 1, 2018, 12:00:00

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' )

More From » string

 Answers
28

Try this :



str.replace(/[ab]/g, function($1) { return $1 === 'a' ? 'b' : 'a' })


example:





console.log(abcabcabc.replace(/[ab]/g, function($1) { return $1 === 'a' ? 'b' : 'a' }))




[#55291] Monday, January 29, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
beatriceisabelad

Total Points: 710
Total Questions: 107
Total Answers: 99

Location: Cayman Islands
Member since Sat, Sep 17, 2022
2 Years ago
beatriceisabelad questions
Fri, Apr 2, 21, 00:00, 3 Years ago
Fri, Jun 19, 20, 00:00, 4 Years ago
Tue, Dec 3, 19, 00:00, 5 Years ago
Wed, Oct 16, 19, 00:00, 5 Years ago
;