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 π
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! π€
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!