Here’s another fun JavaScript challenge from Edabit.
Given an input string, reverse the string word by word, the first word will be the last, and so on.
Examples
reverseWords(“hello world! ”) ➞ “world! hello”
reverseWords(“a good example”) ➞ “example good a”
Notes:
- A word is defined as a sequence of non-space characters.
- The input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
- Try to solve this in linear time.
const phrase1 ='hello world! '
const phrase2 =' What a CRAZY WORLD! '
const phrase3 ='a good example'
function reverseWords(string) {
return string.split(' ').filter(space => space !== '').reverse().join(' ')
}
reverseWords(phrase1) // 'world! hello'
reverseWords(phrase2) // 'WORLD! CRAZY a What'
reverseWords(phrase3) // 'example good a'
// We can also shorten the function using arrow function syntax:
const reverseWords = (string) =>
string.split(' ').filter(space => space !== '').reverse().join(' ')
// And it will work the same way.
How does this work? First, we use the split method to split the string into an array of words. Then, we use the filter method to remove any empty strings from the array. Next, we use the reverse method to reverse the array. Finally, we use the join method to join the array back into a string.
Notice that by filtering out the original spaces we’re able to remove any duplicates and also remove any leading or trailing spaces. By passing in a spac to the join method, we’re able to add the spaces between words.