Skip to content

Instantly share code, notes, and snippets.

@TastyToast
Last active April 21, 2021 09:08
Show Gist options
  • Save TastyToast/5053642 to your computer and use it in GitHub Desktop.
Save TastyToast/5053642 to your computer and use it in GitHub Desktop.
Truncate helper for Handlebars.js
Handlebars.registerHelper ('truncate', function (str, len) {
if (str.length > len) {
var new_str = str.substr (0, len+1);
while (new_str.length) {
var ch = new_str.substr ( -1 );
new_str = new_str.substr ( 0, -1 );
if (ch == ' ') {
break;
}
}
if ( new_str == '' ) {
new_str = str.substr ( 0, len );
}
return new Handlebars.SafeString ( new_str +'...' );
}
return str;
});
@joshpangell
Copy link

I found it useful to make the truncation respect full words. Here is a revised version that does just that. If there is only one word, then it will truncate the middle of that word.

Handlebars.registerHelper ('truncate', function (str, len) {
    if (str.length > len && str.length > 0) {
        var new_str = str + " ";
        new_str = str.substr (0, len);
        new_str = str.substr (0, new_str.lastIndexOf(" "));
        new_str = (new_str.length > 0) ? new_str : str.substr (0, len);

        return new Handlebars.SafeString ( new_str +'...' ); 
    }
    return str;
});

@TastyToast
Copy link
Author

That's really useful. Thanks for sharing!

@nicolasmendoza
Copy link

Thanks for sharing.

@daveroma
Copy link

Thanks for sharing - one thing, just add a check for str bc if there's no string you'll get an exception thrown...

if (str && str.length > len) { ...

@georgebutter
Copy link

Thanks for sharing!

@tarunsankhla
Copy link

thanks for sharing this worked

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment