Computer >> Computer tutorials >  >> Programming >> Javascript

Reversing the words within keeping their order the same JavaScript


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';

Example

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];
      };
      reversed.push(wordReversed);
   });
   return reversed.join(" ");
};
console.log(reverseWords(str));

Output

And the output in the console will be −

sihT si a gnirts