@consumidor-positivo/ts-utils - v1.13.0
    Preparing search index...

    Function truncateString

    • Truncates a string to the specified length and adds a suffix if necessary.

      This utility is useful for limiting text length for display purposes such as in UI components, summaries, or when space is limited.

      Note: This function handles Unicode characters correctly, including emojis and other surrogate pairs.

      Parameters

      • str: string

        The string to truncate

      • sizeStr: number

        The maximum length of the resulting string without the suffix

      • strSufix: string = ...

        The suffix to append to the truncated string (default: '...')

      Returns string

      The truncated string with the suffix appended, or the original string if no truncation was needed

      import { truncateString } from '@consumidor-positivo/ts-utils';

      // Basic usage with default suffix
      truncateString('This is a long string', 10); // 'This is a...'

      // Using a custom suffix
      truncateString('This is a long string', 10, ' [more]'); // 'This is a [more]'

      // When the string is already shorter than the limit, it's returned unchanged
      truncateString('Short', 10); // 'Short'

      // Works correctly with Unicode characters including emojis
      truncateString('Hello 😊 world', 7); // 'Hello 😊...'