'Reverse whole string while keeping the spaces at the same position

This is the code I have tried. If we input "We are farmers!" it should return "!s rem raferaeW" however the code I have returns "!s remr aferaeW"

function reverseStr(input){

  var array1 = [];  
  var array2 = [];
  var nWord;
  for (var i = 0; i < input.length; i++) {

    array1.push(input[i]);

  }

  var spaces = [];

    for (var i = 0; i < array1.length; i++) {
        if(array1[i] == " ") {
            spaces.push(i);
        }
    }

  console.log(array1);
  console.log(spaces);

  array2 = array1.slice().reverse();

  var spaces2 = [];

  for (var i = 0; i < array1.length; i++) {
        if(array2[i] == " ") {
            spaces2.push(i);
        }
    }

  console.log(spaces2);

  for (var i = spaces2.length - 1; i >=0; i--) {
      array2.splice(spaces2[i], 1);
  }

  console.log(array2);

  nWord = array2.join('');

  console.log(nWord);

  var array3 = [];

  for (var i = 0; i < nWord.length; i++) {
      array3.push(nWord[i]);
  }

  console.log(array3);

  for (var i = spaces.length - 1; i >=0; i = i - 1) {
      array3.splice(spaces[i], 0, " ");
  }

  console.log(array3);

  var anWord = array3.join('');
  return anWord;

}

var input = "We are farmers!";
reverseStr(input);

First I pushed each letter of the input into an array at "array1". Then I made an array for the indexes of the spaces of "array1" called "spaces."

Then "array2" is an array of "array1" reversed.

Then "spaces2" is an array of the indexes for "array2" and then I used a for loop to splice out the spaces in array2. Then "nWord" is "array2" combined to form a new word.

Then "array3" is an array for all of nWord's letters and I used a reverse for loop for try to input spaces into "array3" and using the indexes of the "spaces" array. Unfortunately, it is not returning "!s rem raferaeW" and IS returning "!s remr aferaeW".

I am trying to know how I can use the indexes of the "spaces" array to create spaces in "array3" at indexes 2 and 7.



Solution 1:[1]

Here is my best crack at it.

const reverseStr = (input) => {
  const revArr = input.replaceAll(' ', '').split('').reverse();
  for (let i = 0; i < revArr.length; i++) {
    if (input[i] === ' ') revArr.splice(i, 0, ' ');
  }
  return revArr.join('');
}

Solution 2:[2]

let words="Today Is A Good Day";
let splitWords=words.split(' ')
console.log(splitWords)
let r=[]
let ulta=splitWords.map((val,ind,arr)=>{
    // console.log(val.split('').reverse().join(''))
    return r.push(val.split('').reverse().join(''))
})
console.log(r.join(' '))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TheSkepticApe
Solution 2 Rohith Shetty