Code Lab

Reverse the word order, keep the spaces

HardStrings15 min

Write a function reverseWordOrder(sentence) that returns a new string with the words in reverse order. The spaces between the words stay where they are: 'This is sample text' becomes 'text sample is This'.

  • A word is a run of characters that are not spaces. Punctuation is part of the word.
  • Words are separated only by spaces (no tabs, no line breaks). A gap can be one space or more.
  • Every gap of whitespace keeps its length and its place, also at the start and at the end of the string. Only the words move: ' Hello world ' becomes ' world Hello '.
  • The words themselves are not reversed.
  • A string without words (empty or only spaces) is returned unchanged.

If you split on one space and join back with one space, the gaps move together with the words. A loop or a regular expression that finds the words and the gaps works better.

Examples

reverseWordOrder('This is sample text')

Returns 'text sample is This'

reverseWordOrder('  Hello   world ')

Returns ' world Hello '

reverseWordOrder('a  b c')

Returns 'c b a'

Asked at Amazon · Source

Loading the editor...
  1. InputreverseWordOrder('This is sample text')
    Expected'text sample is This'
  2. InputreverseWordOrder(' Hello world ')
    Expected' world Hello '
  3. InputreverseWordOrder('Hello')
    Expected'Hello'

Hidden tests run on Submit.