function reverseWords(str) {
// 1. Split the string into words
const words = str.split(" ");
// 2. Reverse each word
const reversedWords = words.map(word => {
return word.split("").reverse().join("");
});
// 3. Join the reversed words back into a string
return reversedWords.join(" ");
}
// Example usage:
const inputString = "my love";
const reversedString = reverseWords(inputString);
console.log(reversedString); // Output: ym evol
// More concise version using chaining:
const reverseWordsConcise = (str) => str.split(" ").map(word => word.split("").reverse().join("")).join(" ");
console.log(reverseWordsConcise("hello world")); // Output: olleh dlrow
// Handling multiple spaces and edge cases (empty string, single word, leading/trailing spaces):
function reverseWordsRobust(str) {
if (!str) return ""; // Handle empty string
return str.trim() // Remove leading/trailing spaces
.split(/\s+/) // Split by one or more spaces
.map(word => word.split("").reverse().join(""))
.join(" ");
}
console.log(reverseWordsRobust(" hello world ")); // Output: olleh dlrow
console.log(reverseWordsRobust(" single")); // Output: elgnis
console.log(reverseWordsRobust("")); // Output: ""
// Using a for loop for reversal (slightly more performant for very large words):
function reverseWordWithLoop(word) {
let reversed = "";
for (let i = word.length - 1; i >= 0; i--) {
reversed += word[i];
}
return reversed;
}
function reverseWordsWithLoop(str) {
if (!str) return "";
return str.trim()
.split(/\s+/)
.map(word => reverseWordWithLoop(word))
.join(" ");
}
console.log(reverseWordsWithLoop("hello world")); // Output: olleh dlrow
This provides several versions of the function:
reverseWords
: Basic implementation.reverseWordsConcise
: A more concise version using method chaining.reverseWordsRobust
: Handles multiple spaces, leading/trailing spaces, and empty strings. This is generally the most robust solution.reverseWordsWithLoop
: Uses afor
loop for character reversal within each word. This can be slightly more performant than usingsplit("").reverse().join("")
for very large words, though the difference is usually negligible.
Choose the version that best suits your needs and coding style. The robust version is recommended for most real-world applications. The for
loop version might be preferred if performance is a critical concern and you're dealing with potentially very long words.