Reversing words in a string in JavaScript


We are required to write a JavaScript function that takes in a string. The function should return a new string that has all the words of the original string reversed.

For example, If the string is −

const str = 'this is a sample string';

Then the output should be −

const output = 'siht si a elpmas gnirts';

Example

The code for this will be −

const str = 'this is a sample string';
const reverseWords = str => {
   let reversed = '';
   reversed = str.split(" ")
   .map(word => {
      return word
      .split("")
      .reverse()
      .join("");
   })
   .join(" ");
   return reversed;
};
console.log(reverseWords(str));

Output

The output in the console −

siht si a elpmas gnirts

Updated on: 10-Oct-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements