skip to Main Content

How to remove all emojis from a string if they are not equal to any of the ones in the object?
For example:

let allowedEmojis = {
  '😀': 50,
  '😂': 150,
  '🥳': 500
};

function filterEmojis() {
  // what should I type here?
}

let str = "Helloo 😀😂🥳😡";
str = filterEmojis(str);

console.log(str); // Helloo 😀😂🥳

2

Answers


  1. function filterEmojis(text: string): string {
        const emojiPattern = /[p{Emoji}]/gu;
        const allowedSet = new Set(Object.keys(allowedEmojis));
        let result = '';
    
        for (const letter of text) {
            if (emojiPattern.test(letter) && !allowedSet.has(letter)) {
                continue;
            }
            result += letter;
        }
        return result;
    }
    

    The regex might not pass for all Emojis but this is a simple solution to the problem.

    Login or Signup to reply.
  2. Another, simpler, solution would be to use the callback functionality of String.replace():

    const allowedEmojis = {
      '😀': 50,
      '😂': 150,
      '🥳': 500,
    };
    
    str="Helloo 😀😂🥳😡";
    
    console.log(str.replace(/p{Emoji}/ug, a=>allowedEmojis[a]?a:""))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search