---
title: "Comment by Mads B. Cordes on \"A snippy JS function to trim those long strings\" | Hashnode"
description: "Always good with a great truncate -function! Really only thing I&#39;d lay my finger on, is the fact, that the string now gets 3 characters longer when truncate"
url: "https://hashnode.com/posts/a-snippy-js-function-to-trim-those-long-strings/601d6dd91054fa16dadd7b0a/comment/601db931072bc516ff6f4647"
---

[Discussion](https://hashnode.com/posts/a-snippy-js-function-to-trim-those-long-strings/601d6dd91054fa16dadd7b0a)

Comment [A snippy JS function to trim those long strings](https://hashnode.com/posts/a-snippy-js-function-to-trim-those-long-strings/601d6dd91054fa16dadd7b0a)

[Mads B. Cordes](https://hashnode.com/@madco)

[Feb 5, 2021](https://hashnode.com/posts/a-snippy-js-function-to-trim-those-long-strings/601d6dd91054fa16dadd7b0a/comment/601db931072bc516ff6f4647)

Always good with a great `truncate`\-function!

Really only thing I'd lay my finger on, is the fact, that the string now gets `3` characters longer when truncated.

What I mean is, would it be better to do something like subtracting the length of the ellipsis (...) also, thus making it more compatible with, say, twitter 😇

Also, a way to improve the code maybe:

```
function truncate(string, limit = 160, ellipsis = "...") {
    limit -= ellipsis.length;

    if (string.length >= limit) {
        return string.substring(0, limit) + ellipsis;
    }

    return string;
}
```

This way, the result will become:

```
const t = truncate("Lorem ipsum dolor sit amet", 20);
t // "Lorem ipsum dolor..."
t.length; // 20
"Lorem ipsum dolor sit amet".length; // 26
```

Length is now always 26 chars, instead of truncating on 26, then adding the ellipsis to the end of the string. Though, this is simply a design question! 🤓

Love the article though!

[Brett Thurston](https://hashnode.com/@BrettThurston)

[Feb 5, 2021](https://hashnode.com/posts/a-snippy-js-function-to-trim-those-long-strings/601d6dd91054fa16dadd7b0a/comment/601db931072bc516ff6f4647#reply-601dd3aa1054fa16dadd8318)

This is a wonderful solution! I love the consideration for the ellipses, too. Going to throw this in my utils.js file I take everywhere with me.

And setting the default values in the arguments is a lovely touch. 💯

[Mads B. Cordes](https://hashnode.com/@madco)

[Feb 6, 2021](https://hashnode.com/posts/a-snippy-js-function-to-trim-those-long-strings/601d6dd91054fa16dadd7b0a/comment/601db931072bc516ff6f4647#reply-601dea431054fa16dadd840d)

[Brett Thurston](https://hashnode.com/@BrettThurston)

Thanks! Glad I'd be of help! 🤓
