How to convert Unicode to character which is displayed in web page using JavaScript?
For example:
If I've a string which is Unicode: \u4E45
I wanna display this character to web page using JavaScript. How can I do?
And my second question is that if I've a Chines开发者_Go百科e character: 依
I wanna get its Unicode (\u4F9D) using JavaScript. 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).
This can be seen in this example: 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. This string will have the charCodeAt
method available to get the charCode.
Example can be seen here: http://jsfiddle.net/KyuKE/2/
You can read the documentation for charCodeAt
here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/charCodeAt
Code as following
Convert utf8 to string
let font = '\u5b8b\u4f53';
console.log('font', font); // -> font 宋体
let str = String.raw`${font}`;
console.log('str', str); // -> str 宋体
Convert string to 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:
- Convert a String to Unicode in Javascript | Building on Mud
精彩评论