2013-06-12 111 views
1

同樣的問題this,但UTF-8,而不是ASCII的JavaScript:從UTF-8值創建一個字符串或字符

在JavaScript中,你怎麼能得到一個UTF-8值的字符串表示?

例如如何將「c385」變成「Å」?

或如何將「E28093」變成「 - 」(m dash)?

或如何將「E282AC」變成「€」(歐元符號)?

我的問題不是Hex2Asc的重複。你可以看到:hex2a(「E282AC」)會將字符串轉換爲「 - 」,而不是將其轉換爲「€」(歐元符號)!

+0

看看這個:http://stackoverflow.com/questions/834316/how-to-convert-large-utf-8-strings-into-ascii –

+0

其實同樣的答案。但是,我想知道什麼字符代碼*「c3 85」*將代表?而'\ u00c3'是'Ã',而不是'Å'。 – Bergi

+1

這不是同一個問題。事實上,我所引用的問題與你指出的問題是一致的。維基百科:在UTF-8中,Å的十六進制表示是「c3 85」。答案在那裏它會將字符串轉換爲另一個字符:Ã – BearCode

回答

3

我認爲這會做你想要什麼:

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

學分:

1
var hex = "c5"; 
String.fromCharCode(parseInt(hex, 16)); 

,你必須使用c5,不c3 85裁判:http://rishida.net/tools/conversion/

利爾更多的代碼點和代碼單元

  1. http://en.wikipedia.org/wiki/Code_point
  2. http://www.coderanch.com/t/416952/java/java/Unicode-code-unit-Unicode-code
+0

謝謝,但我需要從UTF-8,而不是從ASCII轉換。 C5是ASCII碼,C3 85是UTF-8編碼。大多數字符不是用ASCII編碼的,但所有字符都是用Unicode編碼的(用UTF-8編碼) – BearCode