Write a function that reverses the order of the words in a line, and use it on every line of the input.
What to build
A function reverseWords(text) that returns its answer, and a loop that calls it for each line.
Requirements
reverseWords(text)returns the words oftextin the opposite order, separated by single spaces.- Each input line is handled separately.
Input
Several lines. Each has words separated by single spaces.
Output
Each line with its words reversed.
Constraints
Each line has from 1 to 50 words.
Example
Input:
hello world
Output:
world hello
Why it works
The three steps, split, reverse and join, each do one small job. Because the function returns a value and does not print, the same function could be used for any other purpose.
Examples
Example 1 · Input
hello world
Expected output
world hello
Example 2 · Input
one two three JavaScript is fun
Expected output
three two one fun is JavaScript
Hints
Hint 1
Write function reverseWords(text) that returns the new string; print what it returns.
Hint 2
split(" "), then reverse(), then join(" ").
Hint 3
Each line is one call: read lines until prompt() gives null.
Solution
Show one correct solution (try it yourself first)
function reverseWords(text) {
return text.split(" ").reverse().join(" ");
}
let line = prompt();
while (line !== null) {
console.log(reverseWords(line));
line = prompt();
}