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
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", "๐ถโ๐ซ๏ธ"]