我正在使用从移动应用中获取emojis作为unicodes
\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18
。
当我试图在webbrowser中渲染它时,它不会渲染。所以我写了另一个函数
emojiString = function(s) {
try{
return eval("(function(){ return '" + s + "'})()");
}catch(err){
console.log("error in EmojiString"+err.stack);
return s;
}
};
当我将unicodes发送到此功能时,一切都很好。但是,当我的字符串有()
时,对于某些特殊字符,它会显示一些错误,例如意外令牌或" Uncaught SyntaxError:无效的Unicode转义序列"。
如何使用unicodes在浏览器中呈现表情符号?
答案 0 :(得分:1)
您的字符串包含\ u200b和\ u200c - 零宽度空格
由于隐藏的零宽度空间
,因此失败
var s = "\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18".replace(/[\u200b-\u200d]/,"")
console.log(s)
这将有效:
var s = document.getElementById("x").innerHTML;
console.log("before removing zero-width spaces",s.length);
s=s.replace(/[\u200b\u200c\u200d\ufeff]/g,"");
console.log("after removing zero-width spaces",s.length)
var em = JSON.parse('{"x":"'+s+'"}')
document.getElementById("y").innerHTML = em.x;
The div below contain zero-width spaces:
<div id="x">\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18</div>
<div id="y"></div>