Reversing and preserving spaces in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a sentence string, str, as the first and the only argument.

Our function is supposed to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

For example, if the input to the function is −

const str = 'this is some sample string';

Then the output should be −

const output = 'siht si emos elpmas gnirts';

Example

Following is the code −

 Live Demo

const str = 'this is some sample string';
const reverseWords = (str = '') => {
   return str.trim()
      .split(/\s+/)
      .map((s) => {
      let res = ''
     
      for (let i = s.length-1; i >= 0; i--) {
         res += s[i]
      }
      return res
   })
   .join(' ');
}
console.log(reverseWords(str));

Output

Following is the console output −

siht si emos elpmas gnirts
raja
Published on 21-Apr-2021 12:36:07
Advertisements