In this article you'll find a method to use whenever you have a long string that may funk up your UI components. I was working on a list item component for a project and found a problem we run into a lot. What I have is a list of cards that bring in...

Markdown supported Β· ββ΅ to post
Always good with a great
truncate-function!Really only thing I'd lay my finger on, is the fact, that the string now gets
3characters 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; // 26Length 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!