javascript detect if a string contains only unicode emojis

荒凉一梦 提交于 2019-12-12 13:09:33

问题


I'm using the following function to replace emojis in a string and is working great:

function doEmoji(s){
    var ranges = [
        '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
        '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
        '\ud83d[\ude80-\udeff]'  // U+1F680 to U+1F6FF
    ];
    var x = s.toString(16).replace(new RegExp(ranges.join('|'), 'g'),' whatever ');
    return x;
};

Now I want to check if that string only contains emojis or space characters. The reason why I want to do this is because I want to replace emojis only if no other characters are present(except space).

Some examples:

Hello how are you? 👼 //do nothing
👨‍👩‍👧 // replace emojis
👨‍👩‍👧 👼 // replace emojis

I'm looking for a simple solution, a regex maybe. Thanks


回答1:


Just a minor adjustment to find if the string has only emojis and spaces...

const ranges = [
  '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
  '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
  '\ud83d[\ude80-\udeff]', // U+1F680 to U+1F6FF
  ' ', // Also allow spaces
].join('|');

const removeEmoji = str => str.replace(new RegExp(ranges, 'g'), '');

const isOnlyEmojis = str => !removeEmoji(str).length;



回答2:


In 2018/2019 there are more emoji added, so I modified a bit bholben's RegExp (source: regextester.com):

const ranges = [
    '\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]',
    ' ', // Also allow spaces
].join('|');

const removeEmoji = str => str.replace(new RegExp(ranges, 'g'), '');

const isOnlyEmojis = str => !removeEmoji(str).length;


来源:https://stackoverflow.com/questions/41079416/javascript-detect-if-a-string-contains-only-unicode-emojis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!