UNPKG

@visulima/string

Version:

Functions for manipulating strings.

54 lines (53 loc) 1.72 kB
import { StringTruncatedWidthOptions } from "./get-string-truncated-width.js"; type TruncateOptions = { /** * Text appended to the string when it is truncated * @default '…' */ ellipsis?: string; /** * Width of the ellipsis string * If not provided, it will be calculated using getStringTruncatedWidth */ ellipsisWidth?: number; /** * The position to truncate the string. * @default 'end' */ position?: "end" | "middle" | "start"; /** * Truncate the string from a whitespace if it is within 3 characters from the actual breaking point. * @default false */ preferTruncationOnSpace?: boolean; /** * Width calculation options */ width?: Omit<StringTruncatedWidthOptions, "ellipsis" | "ellipsisWidth" | "limit">; }; /** * Truncates a string to a specified width limit, handling Unicode characters, ANSI escape codes, * and adding an optional ellipsis. * * ANSI Sequence Handling: * - Valid ANSI sequences (e.g. '\u001b[31m') are preserved and handled as styling * - Incomplete sequences are preserved as-is * - Missing terminators are preserved as-is * @example * ```typescript * // Basic usage * truncate('Hello World', 5); // 'Hello…' * * // With valid ANSI styling * truncate('\u001b[31mRed\u001b[0m Text', 3); // '\u001b[31mRed\u001b[0m…' * * // With invalid ANSI sequence * truncate('\u001b[abcText', 4); // '\u001b[abcText' * ``` * @param input The string to truncate * @param limit Maximum width of the returned string * @param options Configuration options for truncation * @returns The truncated string with ellipsis if applicable */ declare const truncate: (input: string, limit: number, options?: TruncateOptions) => string; export { TruncateOptions, truncate };