text-clipper
Version:
Fast and correct clip functions for HTML and plain text.
65 lines (64 loc) • 2.54 kB
TypeScript
interface CommonClipOptions {
/**
* By default, we try to break only at word boundaries. Set to true if this is undesired.
*/
breakWords?: boolean;
/**
* Set to `true` if the string is HTML-encoded. If so, this method will take extra care to make
* sure the HTML-encoding is correctly maintained.
*/
html?: boolean;
/**
* The string to insert to indicate clipping. Default: "…".
*/
indicator?: string;
/**
* Maximum amount of lines allowed. If given, the string will be clipped either at the moment
* the maximum amount of characters is exceeded or the moment maxLines newlines are discovered,
* whichever comes first.
*/
maxLines?: number;
}
interface ClipPlainTextOptions extends CommonClipOptions {
html?: false;
}
interface ClipHtmlOptions extends CommonClipOptions {
html: true;
/**
* The amount of characters to assume for images. This is used whenever an image is encountered,
* but also for SVG and MathML content. Default: `2`.
*/
imageWeight?: number;
/**
* Optional list of tags to be stripped from the output. If `true`, all tags are stripped.
*
* Tag names must be specified in lowercase.
*/
stripTags?: Array<string> | true;
}
declare type ClipOptions = ClipPlainTextOptions | ClipHtmlOptions;
/**
* Clips a string to a maximum length. If the string exceeds the length, it is truncated and an
* indicator (an ellipsis, by default) is appended.
*
* In detail, the clipping rules are as follows:
* - The resulting clipped string may never contain more than maxLength characters. Examples:
* - clip("foo", 3) => "foo"
* - clip("foo", 2) => "f…"
* - The indicator is inserted if and only if the string is clipped at any place other than a
* newline. Examples:
* - clip("foo bar", 5) => "foo …"
* - clip("foo\nbar", 5) => "foo"
* - If the html option is true and valid HTML is inserted, the clipped output *must* also be valid
* HTML. If the input is not valid HTML, the result is undefined (not to be confused with JS'
* "undefined" type; some errors might be detected and result in an exception, but this is not
* guaranteed).
*
* @param string The string to clip.
* @param maxLength The maximum length of the clipped string in number of characters.
* @param options Optional options object.
*
* @return The clipped string.
*/
export default function clip(string: string, maxLength: number, options?: ClipOptions): string;
export {};