Code Lab

Words in reverse order

MediumStrings10 min

Write a function reverseWords(sentence) that returns the words of the string in reverse order. The words themselves are not reversed: 'I Love Java' becomes 'Java Love I'.

  • Words are separated by one or more spaces.
  • In the result words are separated by exactly one space, with no spaces at the start or the end.
  • Punctuation stays part of the word.
  • For an empty string or a string of spaces return ''.

Examples

reverseWords('I Love Java')

Returns 'Java Love I'

reverseWords('  one   two ')

Returns 'two one'

Asked at Mphasis · Source

Loading the editor...
  1. InputreverseWords('I Love Java')
    Expected'Java Love I'
  2. InputreverseWords('Hello')
    Expected'Hello'
  3. InputreverseWords('')
    Expected''

Hidden tests run on Submit.