简体   繁体   中英

Ascii unicode string codes to utf8 in javascript

I have string containing unicodes and I'd like to transform them to 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:

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.

I found answer from: Converting unicode character to string format

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)

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.

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