javascript 检测字符串是否只包含 unicode 表情符号

javascript detect if a string contains only unicode emojis

我正在使用以下函数替换字符串中的表情符号,效果很好:

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;
};

现在我想检查该字符串是否仅包含表情符号或 space 个字符。 我想这样做的原因是因为我只想在没有其他字符存在时替换表情符号(space 除外)。

一些示例:

Hello how are you?  //do nothing
‍‍ // replace emojis
‍‍  // replace emojis

我正在寻找一个简单的解决方案,也许是正则表达式。 谢谢

只需稍作调整即可确定字符串是否只有表情符号和空格...

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;

2018/2019年增加了更多表情符号,所以我修改了一点bholben的RegExp(来源: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;

一个简单的解决方案,如果你不想要任何依赖:

containsOnlyEmojis(text) {
  const onlyEmojis = text.replace(new RegExp('[\u0000-\u1eeff]', 'g'), '')
  const visibleChars = text.replace(new RegExp('[\n\r\s]+|( )+', 'g'), '')
  return onlyEmojis.length === visibleChars.length
}

它删除了 unicode 字符集中的所有字符,这些字符是常规字母表和书写符号,并删除了表情符号和其他一些剩余的东西,对于我们的用例来说,这些东西没问题,但这可能是唯一的警告。

聊天集范围来源:https://en.wikipedia.org/wiki/Unicode_block