Reversing words in a string in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 10-Oct-2020 07:59:01
Advertisements