[英]How to convert Unicode to character which is displayed in web page using JavaScript?
For example: 例如:
If I've a string which is Unicode: \久 如果我有一个Unicode字符串:\\ u4E45
I wanna display this character to web page using JavaScript. 我想使用JavaScript在网页上显示此字符。 How can I do?
我能怎么做?
And my second question is that if I've a Chinese character: 依 我的第二个问题是,如果我有汉字:依
I wanna get its Unicode (\依) using JavaScript. 我想使用JavaScript获得其Unicode(\\ u4F9D)。 How can I do?
我能怎么做?
Thank you very much! 非常感谢你!
If you inject a string with unicode characters via javascript into a webpage they will be displayed the way they should automatically (given that the browser innquestion support the display of that character). 如果您通过javascript将带有Unicode字符的字符串注入网页,则会以应自动显示的方式显示它们(假设浏览器查询支持该字符的显示)。
This can be seen in this example: http://jsfiddle.net/KyuKE/1/ 在此示例中可以看到: http : //jsfiddle.net/KyuKE/1/
You can read the data in a textNode by accessing it's data property which will give you a string. 您可以通过访问textNode的data属性来读取其中的数据,该属性将为您提供一个字符串。 This string will have the
charCodeAt
method available to get the charCode. 该字符串将具有可用于获取charCode的
charCodeAt
方法。
Example can be seen here: http://jsfiddle.net/KyuKE/2/ 示例可以在这里看到: http : //jsfiddle.net/KyuKE/2/
You can read the documentation for charCodeAt
here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/charCodeAt 您可以在此处阅读
charCodeAt
的文档: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/charCodeAt
Code as following 代码如下
Convert utf8 to string 将utf8转换为字符串
let font = '\u5b8b\u4f53';
console.log('font', font); // -> font 宋体
let str = String.raw`${font}`;
console.log('str', str); // -> str 宋体
Convert string to utf8 将字符串转换为utf8
function toUnicode(theString) {
var unicodeString = '';
for (var i=0; i < theString.length; i++) {
var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
unicodeString += theUnicode;
}
return unicodeString;
}
toUnicode(str[0]); // -> '\\u5B8B'
I hope it helps. 希望对您有所帮助。
Reference: 参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.