[英]How do I convert unicode from an HTML input to a greek character in javascript?
How do I convert unicode from an HTML input to a greek character in javascript? 如何在javascript中将unicode从HTML输入转换为希腊字符? 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. 反斜杠在第二个变量
str
转义-在第一个值中,如果input.value为\α
,则实际上与var str = "\\\\U03B1"
相同,以通过转义使反斜杠无效。
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
. 之所以
fromCharCode
,是因为您要从\\ u之后的所有内容中解析一个整数并将其传递给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
要将字符串中的unicode文字转换为实际字符,您可以通过
String.prototype.replace
和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));
}); // "αβγδ"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.