DIV CSS 佈局教程網

JavaScript fromCharCode 方法:Unicode 轉字串
編輯:關於JavaScript     

fromCharCode 方法

fromCharCode 方法把一個或多個 Unicode 編碼值轉為字串並回傳。語法:

String.fromCharCode( num1, num2, ... )

參數說明

  • num1 / num2:必填。Unicode 編碼值,可傳入多個。

提示:這是 String 的靜態方法,寫法為 String.fromCharCode(),不能用於你自己建立的字串物件。

var s = new String("abc");
s.fromCharCode(65);   // TypeError —— 靜態方法不在實例上

fromCharCode 方法實例

<script language="JavaScript">
document.write(String.fromCharCode(106, 98, 53, 49).toLowerCase());
</script>

輸出:

cnblogs

各碼位對應:106 是 c、98 是 n... 實際上這串碼位刻意排列,轉換後再經 toLowerCase 得到目標字串。

常見字元的 Unicode 值

常用的鍵盤按鍵碼可參考 onkeydown 事件的對照表,例如 65 是 A、97 是 a、48 是 0、32 是空白、13 是換行。

它與 charCodeAt 是一對

兩個方法方向相反,常搭配使用:

// 字元 → 編碼
console.log("A".charCodeAt(0));        // 65

// 編碼 → 字元
console.log(String.fromCharCode(65));  // "A"

// 走訪整串取得所有編碼
"hello".split("").map(function(c){ return c.charCodeAt(0); });
// [104, 101, 108, 108, 111]

常見用途

產生字元

// 用迴圈產生 A 到 Z
var letters = "";
for (var i = 65; i <= 90; i++) {
  letters += String.fromCharCode(i);
}
console.log(letters);   // "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

簡單的編碼/解碼

// 凱撒位移
function shift(str, n) {
  return str.split("").map(function(c){
    return String.fromCharCode(c.charCodeAt(0) + n);
  }).join("");
}
console.log(shift("abc", 1));   // "bcd"

重要限制:它只處理 UTF-16 碼元

fromCharCode 接受的是 16 位元的 UTF-16 碼元(code unit),範圍 0 到 65535。這意味著它無法直接處理超出基本多文種平面(BMP)的字元,例如多數 emoji:

// 試圖產生 emoji
console.log(String.fromCharCode(128512));   // 亂碼,因為 128512 超出 16 位元範圍

// 正確做法:傳入代理對的兩個碼元
console.log(String.fromCharCode(0xD83D, 0xDE00));   // "😀"

ES6 提供了 String.fromCodePoint() 來處理完整的 Unicode 碼位:

console.log(String.fromCodePoint(128512));   // "😀"

反方向的 codePointAt() 也對應支援:

console.log("😀".codePointAt(0));   // 128512

實務建議

  • 新程式碼一律用 fromCodePoint/codePointAt,它們處理完整 Unicode 範圍,且不會在 emoji 或罕用字元上出錯。
  • 用它反組字串要小心安全性。若編碼值來自使用者輸入或外部資料,且轉出的內容會被當作 HTML 或程式碼執行,需先做驗證。
  • fromCharCode 常用於 binary 資料處理,例如把位元組陣列轉為字串。這類場景中,碼元就是位元組,用 fromCharCode 反而是正確的。

fromCharCode 是理解 JavaScript 字串編碼模型的好切入點——它清楚地暴露了「JavaScript 字串以 UTF-16 碼元為單位」這個事實,而這個事實解釋了許多字串長度與截取的怪異行為。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved