Fork me on GitHub

Ahad Bokhari

Reversing a String With JavaScript

Edit   ·   words

Just for a little fun, I was thinking of a couple of ways to reverse a string. This seems like a pretty mundane task, but it could very easily crop up in an interview question.

The first implementation one could think of would be relatively easy:

javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
function reverseStr(s) {
return s.split('').reverse.join('');
}

console.log(revStr("Reversing a string"));

// we can rewrite this using String.prototype
String.prototype.reverse = function() {
return this.split('').reverse().join('');
}

var str = 'using String.prototype to reverse a string';
str.reverse();

The second implementation I thought of was using charat and length, which can be considered quite a crude method.

javascript
1
2
3
4
5
6
7
8
var string = "Having fun with reversing strings!!";

var i = string.length;
i = i -1;

for (var x = i; x > 0; x--) {
console.log(string.charAt(x));
}

Perhaps a third implementation that’s pretty fast is using a simple for loop

javascript
1
2
3
4
5
6
function reverseStr(s) {
for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
return o;
}

console.log(reverseStr("Isn't this fun?"));

So I did a little more research and went over to a post on Stack Overflow where there were quite a few implementations with solid examples. Turns out that the first implementation should not be used:

javascript
1
2
3
4
5
6
7
8
// never use this or a similar method!!
function reverseStr(s) {
return s.split('').reverse.join('');
}

// using a good string to test our reverse function: 'foo 𝌆 bar mañana mañana'
console.log reverseStr('foo 𝌆 bar mañana mañana')
'anãnam anañam'

The simple reason being is explained quite well:

Why? Because it contains an astral symbol (𝌆) (which are represented by surrogate pairs in JavaScript) and a combining mark (the ñ in the last mañana actually consists of two symbols: U+006E LATIN SMALL LETTER N and U+0303 COMBINING TILDE).

To properly reverse a string there is a library written by Mathias, is written as a JavaScript library and is capable of Unicode-aware string reversal. It also has a utility/binary so you can reverse strings in your terminal as well :)