How to reverse each word in a sentence
1061

I was asked this question during an interview and had to solve it using JavaScript. The solution is actually very simple if you know the array and string funcitons.

My Solution:

var str = "This is a simple sentence";

var reverseStr = str.split(" ").map(e=>[...e].reverse().join("")).join(" ")
console.log(reverseStr);

//Output: sihT si a elpmis ecnetnes

Explanation:

  • Split the string with space as the delimiter.
  • Then map each word to an array of letters using spread operator
  • Reverse each word in each array and join the the letters
  • Finally join these reversed words with space in between each words

Disclaimer: I know this is not an optimal solution, but the interviewer will be impressed that you were able to solve it in a single line.

Hope this helps.

Comments (2)