This page looks best with JavaScript enabled

Reverse a String in Javascript

 ·   ·  ☕ 2 min read

Oh.. why? Why should we work on theoritical algo problems when we could develop the next Instagram or Salesforce.com?

Because, son - you have to learn the different paths to glory. Why take the longer path when it can be shorter?

That aside: let us look at multiple ways of reversing a string in Javascript.

The best and easiest way

Convert to array and back.

1
2
const txt = "abcxyz";
console.log(txt.split("").reverse().join(""));
Prove that I know ‘modern’ functions

Aka - use reducer to reverse.

1
2
3
const txt = "abcxyz";
const rev = [...txt].reduceRight((revStr, char) => (revStr += char));
console.log(rev); // zyxcba

Or, just use a for.

More of the same

Yep, more ESXX. Use a map.

1
2
3
const txt = "abcxyz";
const revArr = [...txt].map((_, char, arr) => arr[arr.length - 1 - char]);
console.log(revArr.join("")); // zyxcba
Be super object oriented in the wrong language

In fact you can use prototypes everywhere, but below is a cool implementation using RTL override.
You may have to use browser console if you are unable to see this code in action in your favourite console.

1
2
3
4
5
6
7
8
String.prototype.reverse = function () {
  return "\u202E" + this;
};

// RTL
var txt = "\u202E" + "abcxyz";

console.log("txt.reverse(): ", txt.reverse());
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things