Reversing and preserving spaces in JavaScript


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


Following is the code −

 Live Demo

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


Following is the console output −

siht si emos elpmas gnirts