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 Chinese character: 依
I wanna get its Unicode (\u4F9D) using JavaScript. How can I do?
Thank you very much!
To convert Unicode values to characters in JavaScript, use the fromCharCode () string method. You can try to run the following code to convert Unicode to character − How to use Unicode and Special Characters in Tkinter?
JavaScript based Solution One another way is to convert each special character to its respective HTML code using javascript. Within the script we will replace all the special charters with the help of a regular expression which is “&#” + ASCII value of character + “;”.
The charCodeAt () is a built-in JavaScript method that returns the Unicode of the character at a specified index (position) in a string. The index of the first character is 0, and the second is 1. The index of the last character is string length – 1. Index – It is an index number of our string. By default, it is 0.
Character Encoding in JavaScript 1 Unicode Escape. We can store any character in a single using string literal in JavaScript, which is by putting character or sequence of characters in a single or double-quoted string. 2 ASCII Charset. ... 3 UTF Charset. ... 4 Mixed Characters. ... 5 Length of a string. ...
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With