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
Top comments (3)
This code is actually not correct. If a string is presented which has it's first word greater than the maximum length, it will only return ellipsis.
A correct one which accounts for this edge case is:
So one line doesn't cut it here.
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.