Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

extract string emojis from text

i want to extract string emojis from string to array of string.
Previously, i had this regex:

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

and i was using it like this:

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

from text like this: '๐Ÿ˜„123๐Ÿ˜' i was getting : ["๐Ÿ˜„","123","๐Ÿ˜"]
and then i was iterating on array and rendering text or img when i found string emoji

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem is some of emoji has double uni code or some other code stuff, just like: '๐Ÿ˜ถโ€๐ŸŒซ๏ธ' my regex couldnt find so i installed package emoji-regex

I cant manage some method to get array of text and emojis like ["๐Ÿค‘", "456", "๐Ÿ˜ถโ€๐ŸŒซ๏ธ"]

I triend match(), split(), etc. Anything i tried, gives me only text ["456"] or only emojis ["๐Ÿค‘", "๐Ÿ˜ถโ€๐ŸŒซ๏ธ"]

How can i achieve it to get array i can iterate through and render my when i find string emoji or just #text like i was doing before. I have separate file with key string emoji and value to img url, just like that

{
  emoji: '๐Ÿ˜€',
  imageUrl: '/emojis/smileys&people/1f600.png',
},

Thank you for your help

I was using methods like match(), split(), matchAll(), i tried to replace() and return jsx, and package ‘react-string-replace’

>Solution :

There’s a lib for that npm install emoji-regex

Use it with match

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", "๐Ÿ˜ถโ€๐ŸŒซ๏ธ"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading