Daniel Escobedo

Reversing a JavaScript String

Introduction
Reversing a JavaScript String

JavaScript strings do not have in place mutator methods like arrays do:

var arr = [ 'f', 'o', 'o' ];

arr.reverse();

arr; // Array [ 'o', 'o', 'f' ];

Since strings are immutable, we need a hack to accomplish the above with a string:

var str = 'bar';

str.split('').reverse().join('');

str; // 'rab'

The above hack converts the string into an array with split(), performs the reverse as we did with the arr array, and then converts it back to a string with join().


Strings should not be looked at as arrays of characters. If you need to manipulate strings, it is probably best to store them as arrays rather than strings. You can then call join() on the array to convert it to string.

Author

Daniel Escobedo

I'm a JavaScript developer who loves to code. I'm always reading and learning new technologies and tools to better my skills and workflow.

View Comments
Next Post

JavaScript Equality Test with Machine Epsilon in ES6

Mastodon