DEV Community

Discussion on: 5 JavaScript functions to add to your utilities library

Collapse
 
yerac profile image
Rich

Nice. My only comment would be that the ellipsis cut-off should probably subtract the length of the ellipsis, as typically you may want to conform to a database field size. I.e varchar(100) you could end up with 103 chars including the ellipsis,

so like:

function summarize(str, max) {
  return str.length > max ? str.substring(0, max-3) + '...' : str;
}
Collapse
 
slowmove profile image
Erik Hoffman

Even better, it should split at the end of a word and not in the middle of one

function summarize(str, max) {
  if (str.length <= max) return str;
  const subString = str.substring(0, max - 1);
  return subString.substring(0, subString.lastIndexOf(" ")) + "...";
}
Collapse
 
mottie profile image
Rob Garrison

Even better, use the unicode ellipsis (; \u2026).