TS-Scribe - v1.2.0
    Preparing search index...

    Function truncate

    • Truncates a string to a specified maximum length, optionally adding an ellipsis and preserving whole words when truncating.

      Parameters

      • text: string

        The string to truncate.

      • maxLength: number

        The maximum length of the string, including the ellipsis.

      • Optionaloptions: { ellipsis?: string; preserveWords?: boolean }

        Optional configuration for truncation.

        • Optionalellipsis?: string

          The string to append to indicate truncation. Default is '...'.

        • OptionalpreserveWords?: boolean

          Whether to preserve whole words when truncating. When true, truncation occurs at the last space within the allowed range. If no space exists in that range, it falls back to hard truncation at maxLength to guarantee the output never exceeds maxLength. Default is false.

      Returns string

      The truncated string with an ellipsis if necessary, or the original string if it's within the length limit.

      If maxLength is less than or equal to the length of the ellipsis.

      truncate('This is a long string that should be truncated', 20); // "This is a long str..."
      truncate('This is a long string that should be truncated', 20, { preserveWords: true }); // "This is a long..."
      truncate('Supercalifragilistic', 10, { preserveWords: true }); // "Supercali..." (no space — hard truncation)
      truncate('Short text', 20); // "Short text"
      truncate('Short text', 6); // "Sho..."