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


Top comments (5)

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
 
martinkr profile image
Martin Krause

Hi Alex,

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

Cheers!

Collapse
 
martinkr profile image
Martin Krause

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
 
frankwisniewski profile image
Frank Wisniewski • Edited
const reverseWords = ([...str]) => str.reverse().join``.split` `.reverse().join` `
Enter fullscreen mode Exit fullscreen mode