3

I know it's possible in JavaScript to swap two integer values with the XOR option, thus eliminating the need of a temporary variable:

a = 14; b = 27; a^=b; b^=a; a^=b;
// a == 27 and b == 14

But is there a similar no-temp technique in JavaScript for swapping strings?

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Eliseo D'Annunzio
  • 592
  • 1
  • 10
  • 26
  • I *suppose* you could XOR two strings over each other (and you'll have to make something up for when the lengths aren't equal) ... but why? Even to swap two numbers this is a nice trick, but nothing more. – Jongware Sep 24 '14 at 21:34
  • 3
    This might help you out. http://stackoverflow.com/questions/16201656/how-to-swap-two-variables-in-javascript – Garrett Kadillak Sep 24 '14 at 21:34
  • 3
    @GarrettKadillak thanks. That accepted answer is just wow – Yuriy Galanter Sep 24 '14 at 21:36

3 Answers3

15

Alternative swapping methods

ES6 only

ES6's new destructuring assignment syntax:

[a, b] = [b, a]

ES5 compatible

There is an universal single line swapping method that doesn't involve creating new temp variables, and uses only an "on-the-fly" array, here it is:

var a = "world", b = "hello";
b = [a, a = b][0];

console.log(a, b); // Hello world

Explanation:

  • a=b assigns the old value of b to a and yelds it, therefore [a, a=b] will be [a, b]
  • the [0] operator yelds the first element of the array, which is a, so now b = [a,b][0] turns into b = a

Then, for strings only, you can also do this:

var a = "world", b = "hello";
a = b + (b = a, "");

console.log(a, b); // Hello world

You can replace the "" with a 0 if you want to do this with numbers.

Explanation:

  • (b = a, "") assigns the old value of a to b and yelds an empty string
  • now you have a = b + "", and since that b + "" === b, the old value of b is assigned to a

Performance benchmarks

At this page you can find and run a benchmark of different swapping methods. The result of course varies between browser and JS engine versions.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • Interesting, especially considering the universal single line swapping method also is capable of swapping any two object values regardless of their nature... Thanks! – Eliseo D'Annunzio Sep 29 '14 at 00:28
4

Here comes a ES6 solution

We can do the Destructuring Assignment and swap like a boss.

var a = "Hello", b = "World!";
console.log(a, b); // Hello World!
[a, b] = [b, a]; //
console.log(a, b); // World! Hello
Swaggerboy
  • 339
  • 1
  • 2
  • 15
-1

We can use string replace() method to achieve this!

By using regular expression: "/(\w+)\s(\w+)/"

const name = "Akash Barsagadey";
const swapName = name.replace(/(\w+)\s(\w+)/, "$2 $1");

console.log(swapName); //Barsagadey Akash