代码之家  ›  专栏  ›  技术社区  ›  Dawken

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

  •  1
  • Dawken  · 技术社区  · 12 月前

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

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

    我是这样使用的:

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

    来自这样的文本: '😄123😁' 我得到了: ["😄","123","😁"] 然后,当我发现字符串表情符号时,我正在数组上迭代并呈现文本或img

    问题是一些表情符号有双uni代码或其他代码,就像: '😶‍🌫️' 我的regex找不到,所以我安装了包 emoji-regex

    我无法找到一些方法来获得文本和表情符号数组,比如 ["🤑", "456", "😶‍🌫️"]

    我尝试match()、split()等。我尝试的任何东西都只给我文本 ["456"] 或仅表情符号 ["🤑", "😶‍🌫️"]

    当我找到字符串表情符号或像以前一样只是#text时,我如何实现它来获得我可以迭代并渲染的数组。我有一个单独的文件,其中包含关键字字符串表情符号和img url的值,就像这样

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

    谢谢你的帮助

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

    1 回复  |  直到 12 月前
        1
  •  0
  •   Ricardo Gellman    12 月前

    有一个自由 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", "😶‍🌫️"]