From fb798ce895508a51f96ab019426ac27778772c0a Mon Sep 17 00:00:00 2001 From: Lim Chee Aun Date: Tue, 8 Aug 2023 14:04:12 +0800 Subject: [PATCH] Recode EmojiText, fix bug for some emojis not being replaced --- src/components/emoji-text.jsx | 40 ++++++++++++----------------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/src/components/emoji-text.jsx b/src/components/emoji-text.jsx index 041f3c62..caa94215 100644 --- a/src/components/emoji-text.jsx +++ b/src/components/emoji-text.jsx @@ -2,41 +2,29 @@ function EmojiText({ text, emojis }) { if (!text) return ''; if (!emojis?.length) return text; if (text.indexOf(':') === -1) return text; - - const components = []; - let lastIndex = 0; - - emojis.forEach((shortcodeObj) => { - const { shortcode, staticUrl, url } = shortcodeObj; - const regex = new RegExp(`:${shortcode}:`, 'g'); - let match; - - while ((match = regex.exec(text))) { - const beforeText = text.substring(lastIndex, match.index); - if (beforeText) { - components.push(beforeText); - } - components.push( + const regex = new RegExp( + `:(${emojis.map((e) => e.shortcode).join('|')}):`, + 'g', + ); + const elements = text.split(regex).map((word) => { + const emoji = emojis.find((e) => e.shortcode === word); + if (emoji) { + return ( {shortcode}, + /> ); - lastIndex = match.index + match[0].length; } + return word; }); - - const afterText = text.substring(lastIndex); - if (afterText) { - components.push(afterText); - } - - return components; + return elements; } export default EmojiText;