繁体   English   中英

用表情符号替换字符串

[英]Replace string with emoji

给定是具有表示表情符号的代码的输入字段。 我现在想用相应的表情符号替换此代码。

我的想法是用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"> 

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

你需要...

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

 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]')); // 😎 

为了与IE兼容,请按照此处的详细说明使用String.fromCharCode或者根据规范直接转换为16位代理对:

 // 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]')); // 😎 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM