Created
April 12, 2013 23:49
-
-
Save JohnMurray/5376090 to your computer and use it in GitHub Desktop.
Explanation of JS string reversal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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