const reverseWords = (str) => str.split(" ").map((word) => [...word].reverse().join("")).join("");
Returns the string with all words reversed
Improved version with unicode support
const reverseWords = (str) => str.replace(/(\p{L}+)/gu, (word) => [...word].reverse().join(''));
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
Top comments (5)
This would put the punctuation at the start of the last word, so let me suggest an improved version:
Hi Alex,
thank you for taking the time to improve the code.
I like your Idea and updated the article.
Cheers!
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!
We could also use the new RegExp Extension for Unicode property classes and use
/(\p{L}+)/gu
as the RegExp.