DEV Community

Cover image for 1 line of code: How to reverse all words of a string
martin krause
martin krause

Posted on

1 line of code: How to reverse all words of a string

const reverseWords = (str) =>  str.split(" ").map((word) => [...word].reverse().join("")).join("");
Enter fullscreen mode Exit fullscreen mode

Returns the string with all words reversed


Improved version with unicode support

const reverseWords = (str) => str.replace(/(\p{L}+)/gu, (word) => [...word].reverse().join(''));
Enter fullscreen mode Exit fullscreen mode

The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Subscribe to the weekly modern frontend development newsletter


Discussion (6)

Collapse
lexlohr profile image
Alex Lohr

This would put the punctuation at the start of the last word, so let me suggest an improved version:

const reverseWords = (str) => str.replace(/\w+/g, (word) => [...word].reverse().join(''))
Enter fullscreen mode Exit fullscreen mode
Collapse
lukeshiru profile image
Luke Shiru

The problem with this approach is it doesn't support unicode characters such as "Γ±", and the other issue that comes from that is reversing unicode chars with [...word] will mess things up:

[..."πŸ‘¨β€πŸ‘¨β€πŸ‘§β€πŸ‘§"] // ["πŸ‘¨", "", "πŸ‘¨", "", "πŸ‘§", "", "πŸ‘§"]
Enter fullscreen mode Exit fullscreen mode

To solve this we can use Intl.Segmenter like this:

[...(new Intl.Segmenter()).segment("πŸ‘¨β€πŸ‘¨β€πŸ‘§β€πŸ‘§")].map(({ segment }) => segment) // ["πŸ‘¨β€πŸ‘¨β€πŸ‘§β€πŸ‘§"]
Enter fullscreen mode Exit fullscreen mode

This way you make sure you're splitting words without messing with unicode values.

Collapse
martinkr profile image
martin krause Author

Hey everyone,

thank you both for your thoughtull contribution.
After comparing the support tables for JavaScript built-in: Intl: Segmenter and JavaScript built-in: RegExp: unicode I perfer staying with the Regular Expression @lexlohr proposed.

I updated the script and the code as well as the testcases to inlcude unicode support.

Cheers!

Collapse
lexlohr profile image
Alex Lohr

We could also use the new RegExp Extension for Unicode property classes and use /(\p{L}+)/gu as the RegExp.

Collapse
martinkr profile image
martin krause Author

Hi Alex,

thank you for taking the time to improve the code.
I like your Idea and updated the article.

Cheers!

Collapse
frankwisniewski profile image
Frank Wisniewski • Edited on
const reverseWords = ([...str]) => str.reverse().join``.split` `.reverse().join` `
Enter fullscreen mode Exit fullscreen mode