DEV Community

Cover image for 1 line of code: How to truncate a string at word boundaries
martin krause
martin krause

Posted on

1 line of code: How to truncate a string at word boundaries

const truncateAfterWord = (str, chars, placeholder = '') =>  str.length < chars ? str : `${str.substr( 0, str.substr(0, chars - placeholder.length).lastIndexOf(" "))}${placeholder}`;
Enter fullscreen mode Exit fullscreen mode

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


Subscribe to the weekly modern frontend development newsletter


Discussion (2)

Collapse
moopet profile image
Ben Sinclair

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!

Collapse
lionelrowe profile image
lionel-rowe

I guess a reasonable interpretation of "one-liners" is anything you can reasonably do without semicolons or newlines.