1. Reverse the words in the sentence “today is wednesday!” so that it becomes “wednesday is today!”
Model answer
function reverseWords(sentence) {
// Split on whitespace, reverse the word order, and join with single spaces.
return sentence.trim().split(/\s+/).reverse().join(" ");
}
console.log(reverseWords("today is wednesday!")); // "wednesday! is today"
To match the requested output exactly—"wednesday is today!"—the exclamation mark must remain at the end of the sentence rather than attached to the last word. Here is an implementation that preserves trailing punctuation:
function reverseWordsPreservingTrailingPunctuation(sentence) {
const match = sentence.match(/^(.*?)([!?.]+)?$/);
const words = match[1].trim().split(/\s+/).reverse();
const punctuation = match[2] || "";
words[words.length - 1] += punctuation;
return words.join(" ");
}
console.log(reverseWordsPreservingTrailingPunctuation("today is wednesday!"));
// "wednesday is today!"
- The second version treats final punctuation as sentence-level punctuation and attaches it to the final word after reversal.
- It assumes the input contains at least one word.
Complexity: Time O(n); space O(n).