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


Top comments (3)

Collapse
 
netik profile image
John Adams

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:

export function truncateString(str: string, maxLength: number) {
    if (str.length <= maxLength) {
        return str;
    }
    // do we have a space? If not, truncate the word.
    if (str.lastIndexOf(' ') === -1) {
        return str.substr(0, maxLength) + '...';
    }

    if (str.lastIndexOf(' ', maxLength) === -1) {
        return str.substr(0, maxLength) + '...';
    }

    return str.substr(0, str.lastIndexOf(' ', maxLength)) + '...';

}
Enter fullscreen mode Exit fullscreen mode

So one line doesn't cut it here.

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.