Skip to content Skip to sidebar Skip to footer

Javascript: Create A String Or Char From An Utf-8 Value

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 '

Solution 1:

I think this will do what you want:

functionconvertHexToString(input) {

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

    // build a hex-encoded representation of your stringfor (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:

Solution 2:

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

Post a Comment for "Javascript: Create A String Or Char From An Utf-8 Value"