How to reverse each word of a sentence in JavaScript
In this article, we will show you how to reverse each word of a sentence in JavaScript.
Code Snippet to reverse each word in a string
Here’s an example code snippet in JavaScript that demonstrates how to reverse each word in a string:
function reverseWords(str) {
// Split the string into an array of words
const words = str.split(' ');
// Reverse each word in the array
const reversedWords = words.map(word => {
return word.split('').reverse().join('');
});
// Join the reversed words back into a string
const reversedString = reversedWords.join(' ');
return reversedString;
}
// Example usage
const sentence = "Hello, World! This is a sample string.";
const reversedSentence = reverseWords(sentence);
console.log(reversedSentence);
Output: “olleH, dlroW! sihT si a elpmas gnirts.”
In the reverseWords
function, we split the input string into an array of words using the split
method. Then, we use the map
method to iterate over each word and reverse its characters by splitting, reversing, and joining them back together. Finally, we join the reversed words back into a string using the join
method and return the result.
You can pass any string to the reverseWords
function and it will reverse each word in the sentence, maintaining the original word order.
Enjoy the journey of learning and building amazing things! Happy Coding!