[removed] create a string or char from an UTF-8 va

2019-07-27 10:24发布

Same question as this, but with UTF-8 instead of ASCII

In JavaScript, how can you get a string representation of a UTF-8 value?

e.g. how to turn "c385" into "Å" ?

or how to turn "E28093" into "—" (m dash) ?

or how to turn "E282AC" into "€" (euro sign) ?

My question is NOT a duplicate of Hex2Asc. You can see for yourself: hex2a("E282AC") will transform the string into "â¬" instead of transforming it into "€" (euro sign) !!

2条回答
欢心
2楼-- · 2019-07-27 10:59

I think this will do what you want:

function convertHexToString(input) {

    // split input into groups of two
    var hex = input.match(/[\s\S]{2}/g) || [];
    var output = '';

    // build a hex-encoded representation of your string
    for (var i = 0, j = hex.length; i < j; i++) {
        output += '%' + ('0' + hex[i]).slice(-2);
    }

    // decode it using this trick
    output = decodeURIComponent(output);

    return output;
}

console.log("'" + convertHexToString('c385') + "'");   // => 'Å'
console.log("'" + convertHexToString('E28093') + "'"); // => '–'
console.log("'" + convertHexToString('E282AC') + "'"); // => '€'

DEMO

Credits:

查看更多
姐就是有狂的资本
3楼-- · 2019-07-27 11:00
var hex = "c5";
String.fromCharCode(parseInt(hex, 16));

you have to use c5, not c3 85 ref: http://rishida.net/tools/conversion/

Lear more about code point and code unit

  1. http://en.wikipedia.org/wiki/Code_point
  2. http://www.coderanch.com/t/416952/java/java/Unicode-code-unit-Unicode-code
查看更多
登录 后发表回答