【问题标题】:How to Check if a var contains unicode characters and convert them to emojis如何检查 var 是否包含 unicode 字符并将它们转换为表情符号
【发布时间】:2017-06-18 15:29:51
【问题描述】:

我想将给定的 Unicode 字符转换为表情符号。 从一个函数中,我得到一个字符串,有时其中有表情符号,但作为 Unicode(如 \ud83c\uddee\ud83c\uddf9)。 所以我需要先检查这个函数是否包含这些 Unicode 表情符号,然后我需要将它们转换成表情符号。

通过这行代码,我尝试删除这些 Unicode 字符,但它不起作用。 但现在我需要找到一种方法将这些 Unicode 字符转换为 Emoji,而不是删除它们!

var fullnameWOE = fullname[1].replace(/([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])/g, '')

编辑:仍然找不到解决此问题的方法... 我必须补充一点,我正在从一个 php 文件中获取这个名称包含表情符号的字符串,所以如果有任何机会使用 php 来解决它?

【问题讨论】:

  • 这些 Unicode 已经代表了表情符号,所以转换它们没有意义。
  • 编辑:这是一个 JavaScript 示例:<button onclick='alert ("\\ud83c\\udf54 = \ud83c\udf54");'>Hamburger U+1f354</button>
  • 是的,你是对的,但我从这个函数中得到例如字符串:“Dan\ud83c\uddee\ud83c\uddf9”,当我只提醒“\ud83c\uddee\ud83c\ uddf9" 然后它将被转换为表情符号,但整个字符串不会被转换。
  • 在 jsfiddle.net 上尝试过 alert("Dan\ud83c\uddee\ud83c\uddf9"),它似乎有效。 (编辑:或 Shift+F4 (Scratchpad) 在 Firefox 中)

标签: javascript unicode replace


【解决方案1】:

只需参考这个How to find whether a particular string has unicode characters (esp. Double Byte characters) 来检查是否存在 unicode。

但是为了用表情符号代替,我建议你用字典,因为它会更容易控制。

const raw = 'This string could contain an emoticon: {{example of emoticon unicode}}';

const EMOJS = {
  'example of emoticon unicode': 'REPLACED WITH CORRESPONDING VALUE'
};

function compile(input, dict = EMOJS) {
  return Object
    .keys(dict)
    .reduce(
      (res, emojId) => {
        let tmp;
        do {
          tmp = res;
          
          res = res.replace(emojId, dict[emojId]);
        } while(tmp !== res);
        
        return res;
      },
      input
    )
}

console.log({input: raw, output: compile(raw)});

【讨论】:

    【解决方案2】:

    给你:

    function containsNonLatinCodepoints(s) {
        return /[^\u0000-\u00ff]/.test(s);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-11
      • 2012-01-27
      • 1970-01-01
      • 2021-11-17
      • 2015-10-18
      • 2015-01-15
      • 1970-01-01
      • 2021-05-27
      相关资源
      最近更新 更多