Skip to content

Instantly share code, notes, and snippets.

@JohnMurray
Created April 12, 2013 23:49
Show Gist options
  • Save JohnMurray/5376090 to your computer and use it in GitHub Desktop.
Save JohnMurray/5376090 to your computer and use it in GitHub Desktop.
Explanation of JS string reversal
var str = "hello world";
// Split on the empty character (between every
// letter).
var str_split = str.split(''); // => ['h', 'e', 'l', 'l', ' ', 'w', 'o', 'r', 'l', 'd']
// reverse the resulting array
var str_reverse = str_split.reverse(); // => ['d', 'l', 'r', 'o', 'w', ' ', 'l', 'l', 'e', 'h']
// join each string in the array, delimited by
// and empty string
var str_join = str_reverse.join(''); // => 'dlrow olleh';
/*
* Since we can chain all of these together, we do not need to create variables
* because that is just wasteful and the code is bulkier. So, we can simply do:
*/
str.split('').reverse().join('');
// And to add the function to the JavaScript String prototype
// (remember JS is not object-oriented, it's prototype-based)
// we do:
String.prototype.reverse = function() {
return this.split('').reverse().join('');
}
// then we can do things like
var str_reversed = str.reverse();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment