Reversing text comes up in palindrome checks, right-to-left display tricks, and as the warm-up to many string problems. It also shows how JavaScript stores text: reversing "abπ" the quick way turns the emoji into two broken halves. This problem has three versions: reverse every character, reverse the order of the words, and reverse each word while it stays in its place.
functionreverseString(text) // the characters in reverse orderfunctionreverseWords(text) // the words in reverse orderfunctionreverseEachWord(text) // each word reversed, in place
A word is a run of characters that are not whitespace (spaces, tabs, new lines). Punctuation belongs to the word it touches.
reverseString reverses every character, spaces and punctuation included. An emoji stays one character: "abπ" becomes "πba".
reverseString returns "" for "" and the same character for a single one.
reverseWords returns the words in reverse order, joined by single spaces. Leading, trailing and repeated whitespace (tabs and new lines too) does not appear in the result.
reverseWords returns "" for an empty or blank string.
reverseEachWord reverses the characters of each word and keeps the words in their order.
reverseEachWord keeps every whitespace character exactly where it was, including repeated spaces, tabs and new lines, and keeps an emoji whole.