簡體   English   中英

如何將字符串轉換為 unicode 字符?

[英]How can I convert a string into a unicode character?

在 Javascript 中'\\uXXXX'以 unicode 字符返回。 但是當XXXX部分是一個變量時,我怎樣才能得到一個 unicode 字符呢?

例如:

var input = '2122';
console.log('\\u' + input);             // returns a string: "\u2122"
console.log(new String('\\u' + input)); // returns a string: "\u2122"

我能想到的讓它工作的唯一方法是使用eval 但我希望有更好的解決方案:

var input = '2122';
var char = '\\u' + input;
console.log(eval("'" + char + "'"));    // returns a character: "™"

像這樣使用String.fromCharCode()String.fromCharCode(parseInt(input,16)) 當您使用\\u\u003c/code>將 Unicode 值放入字符串時,它會被解釋為十六進制值,因此您需要在使用parseInt時指定基數 (16)。

String.fromCharCode("0x" + input)

要么

String.fromCharCode(parseInt(input, 16))因為它們是 16 位數字 (UTF-16)

JavaScript 在內部使用 UCS-2。

因此, String.fromCharCode(codePoint)不適用於補充 Unicode 字符。 例如,如果codePoint1195580x1D306 ,對於'𝌆'字符)。

如果要創建基於非 BMP Unicode 代碼點的字符串,可以使用Punycode.js的實用函數在 UCS-2 字符串和 UTF-16 代碼點之間進行轉換:

// `String.fromCharCode` replacement that doesn’t make you enter the surrogate halves separately
punycode.ucs2.encode([0x1d306]); // '𝌆'
punycode.ucs2.encode([119558]); // '𝌆'
punycode.ucs2.encode([97, 98, 99]); // 'abc'

從 ES5 開始,您可以使用

String.fromCodePoint(number)

獲得大於 0xFFFF 的 unicode 值。

所以,在每一個新的瀏覽器中,你都可以這樣寫:

var input = '2122';
console.log(String.fromCodePoint(input));

或者如果它是一個十六進制數:

var input = '2122';
console.log(String.fromCodePoint(parseInt(input, 16)));

更多信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint

var hex = '2122';
var char = unescape('%u' + hex);

console.log(char);

將返回“™”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM