简体   繁体   English

用表情符号替换字符串

[英]Replace string with emoji

Given is an input field with an code representing an emoji. 给定是具有表示表情符号的代码的输入字段。 I now want to replace this code with the corresponding emoji. 我现在想用相应的表情符号替换此代码。

The idea was to substitute the value with the unicode but that does not work for me in inputs. 我的想法是用unicode替换值,但这对我的输入不起作用。 Only when I copy the emoji itself into the code, the replacement works. 只有当我将表情符号本身复制到代码中时,替换才有效。

Example: 例:

Given code: [e-1f60e] , 给定代码: [e-1f60e]
converted: 😎 转换: 😎 ,
should be: 😎 应该是:😎

My question: how can I convert the given code to the emoji inside JavaScript? 我的问题:如何将给定的代码转换为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/ JSFiddle: https ://jsfiddle.net/r07qnuoz/1/

You need to... 你需要...

  1. ...find or extract the hexadecimal code point within the string ...在字符串中查找或提取十六进制代码点
  2. ...convert that hexadecimal string to a number ...将十六进制字符串转换为number
  3. ...convert that code point number to a string via String.fromCodePoint ...通过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]')); // 😎 

For compatibility with IE, use String.fromCharCode either as detailed here or by direct conversion to 16-bit surrogate pairs according to the specification : 为了与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