DEV Community

Discussion on: Daily Challenge #263 - Reverse Words

Collapse
dry profile image
Hayden Mankin

Javascript

let reverseWords = (str) => str.replace(/\S+/g, word => [...word].reverse().join(""));

console.log(reverseWords("The quick brown fox jumps over the lazy dog.")); // ehT kciuq nworb xof spmuj revo eht yzal .god
console.log(reverseWords("double spaced words")); // elbuod decaps sdrow
console.log(reverseWords("🞀🞁🞂🞃")); // 🞃🞂🞁🞀

I avoided split("") as it breaks with non BMP characters. The spread operator works just as well for splitting strings into individual characters and won't break astral characters.

Notice how if I use split the output is messed up on my last test case.

let reverseWords = (str) => str.replace(/\S+/g, word => word.split("").reverse().join(""));

console.log(reverseWords("The quick brown fox jumps over the lazy dog.")); // ehT kciuq nworb xof spmuj revo eht yzal .god
console.log(reverseWords("double spaced words")); // elbuod decaps sdrow
console.log(reverseWords("🞀🞁🞂🞃")); // �🞂🞁🞀�