From 4261fec1fa1f00731d713cdca7110ba0e0b76afb Mon Sep 17 00:00:00 2001 From: dangered wolf Date: Sat, 4 Nov 2023 03:52:55 -0400 Subject: [PATCH] Fix scenario where truncating on a UTF-16 character breaks --- src/helpers/utils.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/helpers/utils.ts b/src/helpers/utils.ts index 2a4fb42..6b86c01 100644 --- a/src/helpers/utils.ts +++ b/src/helpers/utils.ts @@ -15,8 +15,23 @@ export const unescapeText = (text: string) => { .replace(/&/g, '&'); }; -export const truncateWithEllipsis = (str: string, maxLength: number): string => - str.length > maxLength ? str.substring(0, maxLength - 1) + '…' : str; +export const truncateWithEllipsis = (str: string, maxLength: number): string => { + const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' }); + const segments = segmenter.segment(str); + let truncated = ''; + let length = 0; + + for (const segment of segments) { + if (length + segment.segment.length > maxLength) { + break; + } + truncated += segment.segment; + length += segment.segment.length; + } + + return truncated.length < str.length ? truncated + '…' : truncated; +}; + const numberFormat = new Intl.NumberFormat('en-US');