Reverse each word and the whole string
MediumStrings10 min
Write a function reverseBoth(sentence) that reverses a string in two ways and returns both results in an object { eachWord, whole }.
eachWord: the characters of every word are reversed, but the words stay in their order.'Hello World'gives'olleH dlroW'.whole: the whole string reversed character by character.'Hello World'gives'dlroW olleH'.- Words are separated by spaces. A word is any group of characters between spaces, so punctuation is part of the word:
'Hi!'gives'!iH'. - In
eachWordevery space stays where it is: double spaces, spaces at the start and spaces at the end too. The input has only spaces as whitespace, no tabs or line breaks. - For the empty string both fields are
''.
You can split the string into words and join them back, but keep every space.
Examples
reverseBoth('Hello World')Returns { eachWord: 'olleH dlroW', whole: 'dlroW olleH' }
reverseBoth('Hi Ann')Returns { eachWord: 'iH nnA', whole: 'nnA iH' }
Asked at JP Morgan · Source
Loading the editor...
- Input
reverseBoth('Hello World')Expected{ eachWord: 'olleH dlroW', whole: 'dlroW olleH' } - Input
reverseBoth('I Love Java')Expected{ eachWord: 'I evoL avaJ', whole: 'avaJ evoL I' } - Input
reverseBoth('Selenium')Expected{ eachWord: 'muineleS', whole: 'muineleS' }
Hidden tests run on Submit