Truncate string at whitespace

OSCC · JavaScript, String · Oct 21, 2020

Truncates a string up to specified length, respecting whitespace when possible.

const truncateStringAtWhitespace = (str, lim, ending = '...') => {
  if (str.length <= lim) return str;
  const lastSpace = str.slice(0, lim - ending.length + 1).lastIndexOf(' ');
  return str.slice(0, lastSpace > 0 ? lastSpace : lim - ending.length) + ending;
};
truncateStringAtWhitespace('short', 10); // 'short'
truncateStringAtWhitespace('not so short', 10); // 'not so...'
truncateStringAtWhitespace('trying a thing', 10); // 'trying...'
truncateStringAtWhitespace('javascripting', 10); // 'javascr...'

Recommended snippets

  • Truncate string

    JavaScript, String

    Truncates a string up to a specified length.

  • Random alphanumeric string

    JavaScript, String

    Generates a random string with the specified length.

  • Pad string

    JavaScript, String

    Pads a string on both sides with the specified character, if it's shorter than the specified length.