let string = "abcdef"; let reverseString = string.split('').reverse().join('');
Let’s go over the code.
This is the split function according to MDN: “The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.”
When we use an empty string as the separator, it simply returns an array with all of the individual characters as elements. So split with an empty string is a very simple way to turn a string into an array.
Next up, we have the reverse method for array objects. Since the split method has converted our string into an array, we can now simply call reverse on it to reverse the array.
This is the join method according to MDN.
“The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.”
Since we are calling join with an empty string as the separator, the elements in the array will simply be concatenated together and returned in a string.
Now we have reversed a string with three simple method calls.
These are the sources I’ve used for this tutorial and will link them in below.
Thanks, pretty simple and easy to use. Just a suggestion, it would be great if you can wrap it in code block so that it would be easy to copy.
Thanks for the suggestion!