* @param {string} text * @returns {number}
(text)
| 16 | * @returns {number} |
| 17 | */ |
| 18 | function getStringWidth(text) { |
| 19 | if (!text) { |
| 20 | return 0; |
| 21 | } |
| 22 | |
| 23 | // shortcut to avoid needless string `RegExp`s, replacements, and allocations |
| 24 | if (!notAsciiRegex.test(text)) { |
| 25 | return text.length; |
| 26 | } |
| 27 | |
| 28 | let width = 0; |
| 29 | text = text.replace(emojiRegex(), (character) => { |
| 30 | width += isNarrowEmojiCharacter(character) ? 1 : 2; |
| 31 | return ""; |
| 32 | }); |
| 33 | |
| 34 | // Use `Intl.Segmenter` when we drop support for Node.js v14 |
| 35 | // https://github.com/prettier/prettier/pull/14793#discussion_r1185840038 |
| 36 | // https://github.com/sindresorhus/string-width/pull/47 |
| 37 | for (const character of text) { |
| 38 | const codePoint = character.codePointAt(0); |
| 39 | |
| 40 | // Ignore control characters |
| 41 | if (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f)) { |
| 42 | continue; |
| 43 | } |
| 44 | |
| 45 | // Ignore combining characters |
| 46 | if (codePoint >= 0x300 && codePoint <= 0x36f) { |
| 47 | continue; |
| 48 | } |
| 49 | |
| 50 | // Ignore Variation Selectors |
| 51 | if (codePoint >= 0xfe00 && codePoint <= 0xfe0f) { |
| 52 | continue; |
| 53 | } |
| 54 | |
| 55 | width += isFullWidth(codePoint) || isWide(codePoint) ? 2 : 1; |
| 56 | } |
| 57 | |
| 58 | return width; |
| 59 | } |
| 60 | |
| 61 | export default getStringWidth; |
no test coverage detected
searching dependent graphs…