用表情符号替换字符串

时间:2017-06-05 11:19:47

标签: javascript

给定是一个带有代表表情符号的代码的输入字段。 我现在想用相应的表情符号替换这段代码。

这个想法是用unicode替换值,但这对我的输入不起作用。只有当我将表情符号本身复制到代码中时,替换才有效。

示例:

给定代码:[e-1f60e]
转换:😎
应该是:

我的问题:如何将给定代码转换为JavaScript中的表情符号?



$("#tauschen").click(function() {
  $('#blub').val(function(index, value) {
    return value.replace('[e-1f60e]', '😎'); // Doesn't work
  });
});

$("#tauschen2").click(function() {
  $('#blub2').val(function(index, value) {
    return value.replace('[e-1f60e]', ''); // Works - but how to convert the given string to an emoji?!
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  Given are strings in an imout field like these, representing an emoji: <strong>[e-1f60e]</strong> </p>

<p>
 Now I want to display them "live" as emojis, instead of only the code: &#x1f60e;
</p>

<input id="blub" type="text" name="test" value="[e-1f60e]">
<input type="submit" value="Test 1" id="tauschen">
<br>

<input id="blub2" type="text" name="test" value="[e-1f60e]">
<input type="submit" value="Test 2" id="tauschen2">
&#13;
&#13;
&#13;

JSFiddle:https://jsfiddle.net/r07qnuoz/1/

1 个答案:

答案 0 :(得分:7)

你需要......

  1. ...在字符串
  2. 中查找或提取十六进制代码点
  3. ...将十六进制字符串转换为number
  4. ...通过String.fromCodePoint
  5. 将该代码点编号转换为字符串

    &#13;
    &#13;
    function convertEmoji(str) {
      return str.replace(/\[e-([0-9a-fA-F]+)\]/g, (match, hex) =>
        String.fromCodePoint(Number.parseInt(hex, 16))
      );
    }
    
    console.log(convertEmoji('[e-1f60e]')); // 
    &#13;
    &#13;
    &#13;

    为了与IE兼容,请使用String.fromCharCode as detailed here或根据the specification直接转换为16位代理对:

    &#13;
    &#13;
    // Convert supplementary plane code point to two surrogate 16-bit code units:
    function surrogate(cp) {
      return [
        ((cp - 0x010000 & 0xffc00) >> 10) + 0xd800,
        (cp - 0x010000 & 0x3ff) + 0xdc00
      ];
    }
    
    function convertEmoji(str) {
      return str.replace(/\[e-([0-9a-fA-F]+)\]/g, function(match, hex) {
        return String.fromCharCode.apply(null, surrogate(Number.parseInt(hex, 16)))
      });
    }
    
    console.log(convertEmoji('[e-1f60e]')); // 
    &#13;
    &#13;
    &#13;