从文本中提取字符串表情符号

问题描述 投票:0回答:1

我想从字符串中提取字符串表情符号到字符串数组中。 以前,我有这个正则表达式:

const regex = /([\u{1F600}-\u{1F64F}])/gu 

我是这样使用它的:

 const parts = text.split(regex).filter(Boolean)

来自这样的文字:

'😄123😁'
我得到:
["😄","123","😁"]
然后当我发现字符串表情符号时,我正在迭代数组并渲染文本或图像

问题是一些表情符号有双uni代码或其他一些代码,就像:

'😶‍🌫️'
我的正则表达式找不到,所以我安装了包
emoji-regex

我无法管理一些方法来获取文本和表情符号数组,例如

["🤑", "456", "😶‍🌫️"]

我尝试了 match()、split() 等。我尝试的任何方法都只给我文本

["456"]
或只给我表情符号
["🤑", "😶‍🌫️"]

当我找到字符串表情符号或只是#text(就像我之前所做的那样)时,我怎样才能实现它来获取可以迭代并渲染我的数组。我有单独的文件,其中包含关键字符串表情符号和 img url 值,就像那样

{
  emoji: '😀',
  imageUrl: '/emojis/smileys&people/1f600.png',
},

谢谢您的帮助

我使用了 match()、split()、matchAll() 等方法,我尝试替换()并返回 jsx,并打包“react-string-replace”

reactjs regex text emoji
1个回答
0
投票

有一个库

npm install emoji-regex

搭配火柴使用

const emojiRegex = require('emoji-regex');

function extractEmojisAndText(input) {
    const regex = emojiRegex();
    const matches = input.match(regex) || [];
    
    let currentIndex = 0;
    const result = [];
    
    matches.forEach(match => {
        // Get the text between the current match and the previous one
        const text = input.substring(currentIndex, input.indexOf(match, currentIndex));
        result.push(text);
        result.push(match);
        currentIndex = input.indexOf(match, currentIndex) + match.length;
    });
    
    // Add any remaining text after the last emoji
    if (currentIndex < input.length) {
        result.push(input.substring(currentIndex));
    }
    
    return result.filter(Boolean); // Filter out any empty strings
}

// Example usage:
const text = '🤑456😶‍🌫️';
const parts = extractEmojisAndText(text);
console.log(parts); // ["🤑", "456", "😶‍🌫️"]
© www.soinside.com 2019 - 2024. All rights reserved.