Truncate string

OSCC · JavaScript, String · Oct 21, 2020

Truncates a string up to a specified length.

  • Determine if String.prototype.length is greater than num.
  • Return the string truncated to the desired length, with '...' appended to the end or the original string.
const truncateString = (str, num) =>
  str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
truncateString('boomerang', 7); // 'boom...'

Recommended snippets

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

  • 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.