Skip to main content

Simple JavaScript function for shortening, or summarizing a string.

function summarizeString(str, limit, appendText) {
  if (str.length <= 0) {
    return '';
  }

  if (!limit) {
    limit = 25;
  }

  if (str.length <= limit) {
    return str;
  }

  if (!appendText) {
    appendText = ' ...';
  }

  str = str.substring(0, limit);
  str = str.replace(/\s+$/, ""); // right trim

  return str + appendText;
}