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?
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?
Share Improve this question edited Sep 24, 2014 at 22:16 Marco Bonelli 69.3k21 gold badges126 silver badges145 bronze badges asked Sep 24, 2014 at 21:30 Eliseo D'AnnunzioEliseo D'Annunzio 5921 gold badge10 silver badges27 bronze badges 3- 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 Commented Sep 24, 2014 at 21:34
- 3 This might help you out. stackoverflow.com/questions/16201656/… – Garrett Kadillak Commented Sep 24, 2014 at 21:34
- 3 @GarrettKadillak thanks. That accepted answer is just wow – suff trek Commented Sep 24, 2014 at 21:36
3 Answers
Reset to default 15Alternative 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 ofb
toa
and yelds it, therefore[a, a=b]
will be[a, b]
- the
[0]
operator yelds the first element of the array, which isa
, so nowb = [a,b][0]
turns intob = 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 ofa
tob
and yelds an empty string- now you have
a = b + ""
, and since thatb + "" === b
, the old value ofb
is assigned toa
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.
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
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