String.prototype.charCodeAt()
charCodeAt() 方法返回一個介於 0 和 65535 之間的整數,表示給定索引處的 UTF-16 碼單元。
charCodeAt() 始終將字串索引為一系列 UTF-16 碼單元,因此它可能會返回獨立的代理碼元。要獲取給定索引處的完整 Unicode 碼點,請使用 String.prototype.codePointAt()。
試一試
const sentence = "The quick brown fox jumps over the lazy dog.";
const index = 4;
console.log(
`Character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(
index,
)}`,
);
// Expected output: "Character code 113 is equal to q"
語法
charCodeAt(index)
引數
返回值
一個介於 0 和 65535 之間的整數,表示指定 index 處字元的 UTF-16 碼單元值。如果 index 超出 0 – str.length - 1 的範圍,charCodeAt() 將返回 NaN。
描述
字串中的字元從左到右索引。第一個字元的索引是 0,名為 str 的字串中最後一個字元的索引是 str.length - 1。
Unicode 碼點範圍從 0 到 1114111 (0x10FFFF)。charCodeAt() 始終返回小於 65536 的值,因為較高的碼點由一對 16 位代理偽字元表示。因此,為了獲得值大於 65535 的完整字元,有必要檢索 charCodeAt(i) 以及 charCodeAt(i + 1)(就像處理一個有兩個字元的字串一樣),或者改用 codePointAt(i)。有關 Unicode 的資訊,請參閱 UTF-16 字元、Unicode 碼點和字形簇。
示例
使用 charCodeAt()
以下示例返回 65,即 A 的 Unicode 值。
"ABC".charCodeAt(0); // returns 65
charCodeAt() 可能會返回獨立的代理碼元,這些代理碼元不是有效的 Unicode 字元。
const str = "𠮷𠮾";
console.log(str.charCodeAt(0)); // 55362, or d842, which is not a valid Unicode character
console.log(str.charCodeAt(1)); // 57271, or dfb7, which is not a valid Unicode character
要獲取給定索引處的完整 Unicode 碼點,請使用 String.prototype.codePointAt()。
const str = "𠮷𠮾";
console.log(str.codePointAt(0)); // 134071
注意: 避免使用 charCodeAt() 來重新實現 codePointAt()。UTF-16 代理碼元到 Unicode 碼點的轉換很複雜,並且 codePointAt() 可能更具效能,因為它直接使用了字串的內部表示。如果需要,請為 codePointAt() 安裝 polyfill。
下面是從 Unicode FAQ 調整的將一對 UTF-16 碼單元轉換為 Unicode 碼點的可能演算法。
// constants
const LEAD_OFFSET = 0xd800 - (0x10000 >> 10);
const SURROGATE_OFFSET = 0x10000 - (0xd800 << 10) - 0xdc00;
function utf16ToUnicode(lead, trail) {
return (lead << 10) + trail + SURROGATE_OFFSET;
}
function unicodeToUTF16(codePoint) {
const lead = LEAD_OFFSET + (codePoint >> 10);
const trail = 0xdc00 + (codePoint & 0x3ff);
return [lead, trail];
}
const str = "𠮷";
console.log(utf16ToUnicode(str.charCodeAt(0), str.charCodeAt(1))); // 134071
console.log(str.codePointAt(0)); // 134071
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-string.prototype.charcodeat |
瀏覽器相容性
載入中…