简体   繁体   English

在JavaScript中将ASCII Unicode字符串代码转换为utf8

[英]Ascii unicode string codes to utf8 in javascript

I have string containing unicodes and I'd like to transform them to utf8. 我有包含Unicode的字符串,我想将它们转换为utf8。 How would you implement this -> 您将如何实施->

input: 输入:

var data = "\u03b1" // actually coming from python remote callback data
var html = "Letter a: " + data
document.getElementByID('input').innerHTML = html

output on div#input is: div#input上的输出是:

Letter a: \u03b1

But it should be: 但是应该是:

Letter a: α

I suspect because "\α" is not written on javascript code, but passed via text variable from python, javascript engine doesn't transform characters to correct form, but keeps them as strings. 我怀疑是因为“ \\ u03b1”不是用javascript代码编写的,而是通过python的text变量传递的,因此javascript引擎不会将字符转换为正确的形式,而是将其保留为字符串。

I found answer from: Converting unicode character to string format 我从找到答案: 将Unicode字符转换为字符串格式

function unicodeToChar(text) {
    return text.replace(/\\u[\dA-Fa-f]{4}/g, 
        function (match) {
            return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
        });
}

Applying in my case: 在我的情况下适用:

var html = "Letter a: " + unicodeToChar(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM