const truncateAfterWord = (str, chars, placeholder = '…') => str.length < chars ? str : `${str.substr( 0, str.substr(0, chars - placeholder.length).lastIndexOf(" "))}${placeholder}`;
Returns the string truncated to the given amount of chars while preserving full words.
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
Discussion (2)
I'm going to suggest an 80-character limit on "one line" code samples, because otherwise I could minimise the code for Excel and call it a one-liner!
I guess a reasonable interpretation of "one-liners" is anything you can reasonably do without semicolons or newlines.