JS Built-ins
Algorithmsbeginner

Reverse Words

πŸ“– Usage Example
function reverseWords(s) {
  return s.split(' ').reverse().join(' ');
}
reverseWords('Hello World'); // 'World Hello'

Reverse word order by splitting on spaces, reversing the array, and joining back.

Reverse Words

Reverse the order of words in a string while keeping each word intact.

"hello world" β†’ "world hello"
"JavaScript is fun" β†’ "fun is JavaScript"

Algorithm:

  1. Split the string into words
  2. Reverse the array of words
  3. Join them back together
function reverseWords(s: string): string {
  // Reverse the order of words in s
}

reverseWords('hello world') // "world hello"
πŸ’‘ Hints (4)
  • β€’ Use split(" ") to split by spaces.
  • β€’ Use reverse() to reverse the array.
  • β€’ Use join(" ") to join with spaces.
  • β€’ This can be done in one line.