Reversing the words within keeping their order the same JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string. The function should reverse each word of the string within (by a word, we mean a substring which is either surrounded by whitespaces on both ends or by a whitespace and string end).

The function should finally return the newly formed string.

For example −

If the input string is −

const str = 'This is a string';

Then the output should be −

const output = 'sihT si a gnirts';


const str = 'This is a string';
const reverseWords = (str = '') => {
   const reversed = [];
   str.split(" ").forEach(el => {
      let wordReversed = "";
      for (let i = el.length - 1; i >= 0; i--){
          wordReversed += el[i];
   return reversed.join(" ");


And the output in the console will be −

sihT si a gnirts
Updated on 25-Nov-2020 05:43:45