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.