Surrogate Pair(代理對)是什麼? 它是 UTF-16 用來表示 U+FFFF 以上字元的做法:把一個 code point 拆成兩個 16 位元的 code unit,前一個落在 0xD800 到 0xDBFF,後一個落在 0xDC00 到 0xDFFF。JavaScript 字串由 UTF-16 code unit 組成,所以 '😀'.length 是 2,不是 1。本文說明 code point 與 code unit 的差別、代理對的換算公式,以及 length、slice、codePointAt、for...of、isWellFormed() 各自怎麼處理它。
字元如何對應成數字(ASCII、Unicode 編號)可前往〈ASCII 是什麼?字元編碼入門〉;Unicode 編號與字元互轉的寫法可前往〈Unicode 轉字元:JavaScript 與 PHP 寫法〉。本文直接從 UTF-16 的 code unit 切入。
Surrogate Pair 是什麼:code point 與 code unit 的差別
先分清楚兩個詞:
- code point(碼位):Unicode 給每個字元的編號,範圍從 0 到 0x10FFFF,寫成
U+1F600這樣的形式。 - code unit(編碼單元):某種編碼形式裡的最小儲存單位。Unicode Standard 的定義是「The minimal bit combination that can represent a unit of encoded text for processing or interchange」;UTF-16 的 code unit 是 16 位元。
UTF-16 的規則是:落在 U+0000 到 U+D7FF 與 U+E000 到 U+FFFF 的 code point,用一個 code unit 表示,數值與 code point 相同;落在 U+10000 到 U+10FFFF 的 code point,用兩個 code unit 表示,這一對就是 Surrogate Pair。Unicode Standard 對 Surrogate Pair 的定義是由一個 high-surrogate code unit 加一個 low-surrogate code unit 組成,且只用於 UTF-16。
| 名稱 | 範圍 | 在代理對中的位置 |
|---|---|---|
| High-surrogate(前導代理) | 0xD800 到 0xDBFF | 第一個 code unit |
| Low-surrogate(尾隨代理) | 0xDC00 到 0xDFFF | 第二個 code unit |
ECMAScript 規格把這兩段稱為 leading surrogate 與 trailing surrogate。0xD800 到 0xDFFF 這段 code point 專供代理對使用,Unicode Standard 說明它們不是 Unicode scalar value,單獨出現的 code unit 屬於 ill-formed(格式不良)。
換算公式:從 code point 算出兩個 code unit
Unicode Standard 的 UTF-16 位元分配(Table 3-5)是:scalar value 大於等於 U+10000 時,先減 0x10000,得到 20 位元的數字,前 10 位元加上 0xD800 成為 high-surrogate,後 10 位元加上 0xDC00 成為 low-surrogate。ECMAScript 規格寫的是反向公式:由前導 c1 與尾隨 c2 還原 code point 是 (c1 - 0xD800) × 0x400 + (c2 - 0xDC00) + 0x10000。
用 U+1F600(😀)當例子:
- 減掉偏移量:
0x1F600 - 0x10000 = 0xF600。 - 取高 10 位元:
0xF600 >> 10 = 0x3D,加上0xD800得0xD83D。 - 取低 10 位元:
0xF600 & 0x3FF = 0x200,加上0xDC00得0xDE00。
所以 U+1F600 在 UTF-16 裡是 D83D DE00。用 JavaScript 寫成:
const cp = 0x1F600 - 0x10000;
const high = 0xD800 + (cp >> 10);
const low = 0xDC00 + (cp & 0x3FF);
console.log(high.toString(16), low.toString(16)); // d83d de00
// 反向還原,對應 ECMAScript 規格的公式
console.log((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000 === 0x1F600); // true
高、低各有 0x400(1,024)個值,兩兩組合共 1,048,576 種,剛好等於 U+10000 到 U+10FFFF 的 code point 數量。
JavaScript 字串是 UTF-16 code unit 的序列
ECMAScript 規格的 The String Type 一節寫明:String 型別是由 16 位元無號整數(elements)組成的有序序列,用來表示文字時,每個 element 視為一個 UTF-16 code unit;字串的 length 是 elements 的數量。MDN 的 String.prototype.length 也說明,這個值是 code unit 的數量,所以可能和實際的字元數不同;一般拉丁字母、常見的 CJK 字元不會有差異,表情符號、數學符號、罕見漢字則要留意。
以下範例在 Node.js v22 執行:
const s = '😀';
console.log(s.length); // 2
console.log(s.charCodeAt(0).toString(16)); // d83d
console.log(s.charCodeAt(1).toString(16)); // de00
console.log(s.codePointAt(0).toString(16)); // 1f600
console.log([...s].length); // 1

length、charCodeAt、codePointAt、slice、isWellFormed()、toWellFormed() 與 encodeURIComponent() 的輸出畫面,終端字型把孤立代理顯示成替代符號。同一個字,length 看 code unit 得 2,charCodeAt(0) 與 charCodeAt(1) 分別拿到前導與尾隨代理,codePointAt(0) 才拿到完整的 0x1F600。
罕見漢字也一樣,'𠮷'(U+20BB7)的 length 是 2,codePointAt(0) 是 0x20bb7;落在 BMP(U+0000 到 U+FFFF)內的常用字如 '測',length 則是 1。
length、slice、charAt 與 split:以 code unit 為單位
規格說明字串操作把每個 element 當成單一 UTF-16 code unit,MDN 也指出字串索引指的是 code unit 的位置。因此這幾個方法都會把代理對當成兩格:
const text = 'A😀B';
console.log(text.length); // 4
console.log(text.charAt(1) === '\uD83D'); // true,只拿到前導代理
console.log(text.slice(0, 2)); // 'A' 加一個孤立的前導代理,終端機常顯示成 A 加一個替換字元(U+FFFD)
console.log(text.split('')); // [ 'A', '\ud83d', '\ude00', 'B' ]
split('') 會依 code unit 切開並拆散代理對,MDN String 頁面的範例 "😄".split("") 結果是兩個孤立代理,行為相同。slice(0, 2) 切在代理對中間,結果留下孤立的前導代理。
要移除字串第一個字元時,遇到代理對就會切錯,寫法可前往〈JavaScript 刪除字串第一個字元〉;下一節的 Array.from() 就是其中一種處理方式。
以 code point 為單位:codePointAt、fromCodePoint、for…of 與 Array.from
MDN 說明 String.prototype[Symbol.iterator]() 依 Unicode code point 迭代,所以 for...of、展開運算子 [...str] 與 Array.from(str) 都會把一組代理對當成一個元素:
const text = 'A😀B';
console.log([...text].length); // 3
console.log(Array.from(text).length); // 3
for (const ch of text) {
console.log(ch, ch.codePointAt(0).toString(16));
}
// A 41
// 😀 1f600
// B 42
codePointAt(index) 的行為,依 MDN 說明:index 位置是前導代理時,回傳整組代理對的 code point;是尾隨代理時,只回傳該尾隨代理的 code unit 值。所以 '😀'.codePointAt(0) 是 0x1F600,'😀'.codePointAt(1) 是 0xde00。
反方向用 String.fromCodePoint(),依 code point 建立字串,代理對由引擎自動組好;對照 String.fromCharCode() 要自己寫出兩個 code unit:
console.log(String.fromCodePoint(0x1F600) === '😀'); // true
console.log(String.fromCharCode(0xD83D, 0xDE00) === '😀'); // true
console.log(String.fromCodePoint(0x1F600).length); // 2
fromCodePoint() 傳入非整數、小於 0 或大於 0x10FFFF 的數字會丟 RangeError;MDN 也提醒,回傳字串的 length 可能比傳入的引數個數多。
| 需求 | 以 code unit 計 | 以 code point 計 |
|---|---|---|
| 字串長度 | str.length | [...str].length |
| 取某位置的字 | str.charAt(i)、str[i] | Array.from(str)[i] |
| 取數值 | charCodeAt(i) | codePointAt(i) |
| 由數值建立字串 | String.fromCharCode() | String.fromCodePoint() |
| 逐字走訪 | for (let i...) 迴圈 | for...of |
孤立代理(lone surrogate)與 isWellFormed()、toWellFormed()
MDN 對 lone surrogate 的說明是:前導代理後面沒有接尾隨代理,或尾隨代理前面沒有接前導代理。孤立代理不代表任何 Unicode 字元;不含孤立代理的字串稱為 well-formed。切到代理對中間的 slice、手動拼接 code unit,都可能產生孤立代理。
與其他系統互動時,孤立代理常出問題。MDN 以 encodeURI() 為例:它碰到孤立代理會丟 URIError,因為 URI 編碼使用 UTF-8,而 UTF-8 沒有孤立代理的編碼。檢查與修復有兩個方法:
String.prototype.isWellFormed():回傳布林值,字串沒有孤立代理才是true。String.prototype.toWellFormed():回傳新字串,把所有孤立代理換成 Unicode 替代字元 U+FFFD。
const bad = 'ab\uD83D';
console.log(bad.isWellFormed()); // false
console.log(bad.toWellFormed().codePointAt(2).toString(16)); // fffd
try {
encodeURIComponent(bad);
} catch (e) {
console.log(e.name); // URIError
}
MDN 標示這兩個方法為 Baseline Widely available,自 2023 年 10 月起各主流瀏覽器都支援。要在更舊的環境執行,就得自己檢查 code unit 範圍或改用別的方式處理。
代理對不等於使用者看到的一個字
用 [...str] 或 Array.from() 迭代只解決代理對,仍然不等於「使用者看到的一個字」。MDN 提醒:以 code point 迭代之外,要逐一走訪 grapheme cluster(字素叢集)需要額外的程式。Unicode UAX #29 把 grapheme cluster 稱為「user-perceived characters」。
家庭 emoji 是常見例子,它由多個 code point 以零寬連接字元(ZWJ)串成,一個畫面上的符號對應多個 code point,每個 code point 又各自佔一或兩個 code unit:
const family = '👨👩👧';
console.log(family.length); // 8
console.log([...family].length); // 5
const seg = new Intl.Segmenter('zh-TW', { granularity: 'grapheme' });
console.log([...seg.segment(family)].length); // 1
Intl.Segmenter 依語系切分文字,可選擇字素、單字或句子;MDN 標示為 Baseline Widely available,自 2024 年 4 月起各主流瀏覽器都支援。需要「畫面上有幾個字」時(例如字數限制、游標位置),用 Intl.Segmenter 的 grapheme 才對。
該用哪一種寫法
- 只處理 BMP 內的文字(拉丁字母、常見中文)且不碰 emoji,
length與slice通常夠用。 - 字串可能含 emoji 或罕見漢字,要數 code point 或逐字處理,用
for...of、[...str]或Array.from()。 - 要在 code point 與字串間轉換,用
codePointAt()與String.fromCodePoint()。 - 要把字串交給
encodeURIComponent()、TextEncoder這類不處理 UTF-16 的功能前,先用isWellFormed()檢查,必要時用toWellFormed()修復。 - 要計算畫面上的字數或做游標移動,用
Intl.Segmenter的grapheme分段。
參考資料與延伸閱讀
- Unicode Standard:Chapter 3 Conformance(D71 到 D77、D91、Table 3-5)
- Unicode UAX #29:Text Segmentation
- ECMAScript® 2027 Language Specification:The String Type(tc39.es)
- MDN:String(UTF-16 characters, Unicode code points, and grapheme clusters)
- MDN:String length
- MDN:String.prototype.codePointAt()
- MDN:String.fromCodePoint()
- MDN:String.prototype.isWellFormed()
- MDN:String.prototype.toWellFormed()
- MDN:Intl.Segmenter
- 站內延伸閱讀:〈ASCII 是什麼?字元編碼入門〉、〈Unicode 轉字元:JavaScript 與 PHP 寫法〉、〈JavaScript 刪除字串第一個字元〉
發佈留言