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