How do I convert unicode from an HTML input to a greek character in javascript? The first example does not work, but the second does.
var str = input.value; \u03B1 (typed into input box)
console.log(str); \u03B1
var str = "\u03B1"; assigned directly
console.log(str); α
The backslash is escaping in the second variable str
- in the first value, if input.value was \α
, it would ACTUALLY be the same as var str = "\\\\U03B1"
to invalidate the backslash by escaping it.
If you want to evaluate the escaped character in the field, you can do so like this:
var str = input.value.replace("\\u", "");
str = String.fromCharCode(parseInt(str, 16));
This works because you are parsing an integer from everything after \\u and passing that into fromCharCode
. Character codes are in integers - you are parsing that code from the original \⎱
code.
To convert unicode literals in strings to actual characters you can just run them though String.prototype.replace
with String.fromCharCode
var str = '\\u03B1\\u03B2\\u03B3\\u03B4'; // "\u03B1\u03B2\u03B3\u03B4"
str.replace(/\\u([\da-fA-F]{4})/g, function (m, $1) {
return String.fromCharCode(parseInt($1, 16));
}); // "αβγδ"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.