UNPKG

string-length

Version:

Get the real length of a string - by correctly counting astral symbols and ignoring ansi escape codes

27 lines (19 loc) 556 B
// eslint-disable-next-line n/prefer-global/process const {stripVTControlCharacters} = globalThis.process?.getBuiltinModule?.('node:util') ?? {}; const segmenter = new Intl.Segmenter(); export default function stringLength(string, {countAnsiEscapeCodes = false} = {}) { if (string === '') { return 0; } if (!countAnsiEscapeCodes && stripVTControlCharacters) { string = stripVTControlCharacters(string); if (string === '') { return 0; } } let length = 0; for (const _ of segmenter.segment(string)) { length++; } return length; }