简体   繁体   English

如何在javascript中将unicode从HTML输入转换为希腊字符?

[英]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.replaceString.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.

相关问题 使用 Javascript,如何将二进制字符串(1 和 0)转换回 Unicode 字符? - Using Javascript, how do I convert a binary string (1s and 0s) back into a Unicode character? 如何将XML文件中的转义unicode字符读入Javascript? - How do I read an escaped unicode character from an XML file into Javascript? 如何将字符串转换为 unicode 字符? - How can I convert a string into a unicode character? 使用 Javascript 从 HTML 中的 Json 转换 unicode - Convert unicode from Json in HTML with Javascript 如何使用JavaScript在HTML标题中正确插入unicode? - How do I correctly insert unicode in an HTML title using JavaScript? 如何从 HTML 输入框运行 javascript 代码? - How do I run javascript code from a HTML input box? 我如何让我的 html 输入元素影响我的 javascript 类对象值(字符名称) - How do i get my html input element to influence my javascript class object value(character name) 如何将包含十六进制 unicode 字符的 innerHTML 更改为另一个与 JavaScript 类似的字符? - How do I change innerHTML which contains hex unicode character for another similar character with JavaScript? Javascript unicode(希腊语)正则表达式 - Javascript unicode (greek) regular expressions 如何使用JavaScript将Unicode转换为显示在网页中的字符? - How to convert Unicode to character which is displayed in web page using JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM