String.prototype.charAt()
charAt() 方法用於返回由給定索引處的單個 UTF-16 碼單元組成的新字串。
charAt() 始終將字串視為 UTF-16 碼單元序列進行索引,因此它可能會返回孤立的代理碼元。要獲取給定索引處的完整 Unicode 碼點,請使用 String.prototype.codePointAt() 和 String.fromCodePoint()。
試一試
const sentence = "The quick brown fox jumps over the lazy dog.";
const index = 4;
console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// Expected output: "The character at index 4 is q"
語法
charAt(index)
引數
返回值
一個字串,表示指定 index 處的字元(恰好一個 UTF-16 碼單元)。如果 index 超出了 0 – str.length - 1 的範圍,charAt() 將返回一個空字串。
描述
字串中的字元從左到右索引。第一個字元的索引是 0,名為 str 的字串中最後一個字元的索引是 str.length - 1。
Unicode 碼點範圍從 0 到 1114111 (0x10FFFF)。charAt() 總是返回一個值小於 65536 的字元,因為較高的碼點由一對 16 位代理偽字元表示。因此,為了獲取值大於 65535 的完整字元,有必要檢索 charAt(i) 和 charAt(i + 1)(就好像處理一個有兩個字元的字串一樣),或者改用 codePointAt(i) 和 String.fromCodePoint()。有關 Unicode 的資訊,請參閱 UTF-16 字元、Unicode 碼點和圖素簇。
charAt() 與使用 方括號表示法在指定索引處訪問字元非常相似。主要區別在於:
charAt()嘗試將index轉換為整數,而方括號表示法則不轉換,直接將index用作屬性名。- 如果
index超出範圍,charAt()返回一個空字串,而方括號表示法返回undefined。
示例
使用 charAt()
以下示例顯示了字串 "Brave new world" 中不同位置的字元。
const anyString = "Brave new world";
console.log(`The character at index 0 is '${anyString.charAt()}'`);
// No index was provided, used 0 as default
console.log(`The character at index 0 is '${anyString.charAt(0)}'`);
console.log(`The character at index 1 is '${anyString.charAt(1)}'`);
console.log(`The character at index 2 is '${anyString.charAt(2)}'`);
console.log(`The character at index 3 is '${anyString.charAt(3)}'`);
console.log(`The character at index 4 is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
這些行顯示以下內容:
The character at index 0 is 'B' The character at index 0 is 'B' The character at index 1 is 'r' The character at index 2 is 'a' The character at index 3 is 'v' The character at index 4 is 'e' The character at index 999 is ''
charAt() 可能會返回孤立的代理碼元,它們不是有效的 Unicode 字元。
const str = "𠮷𠮾";
console.log(str.charAt(0)); // "\ud842", which is not a valid Unicode character
console.log(str.charAt(1)); // "\udfb7", which is not a valid Unicode character
要獲取給定索引處的完整 Unicode 碼點,請使用按 Unicode 碼點拆分的索引方法,例如 String.prototype.codePointAt() 和 將字串展開為 Unicode 碼點陣列。
const str = "𠮷𠮾";
console.log(String.fromCodePoint(str.codePointAt(0))); // "𠮷"
console.log([...str][0]); // "𠮷"
注意: 避免使用 charAt() 重新實現上述解決方案。孤立代理碼元的檢測及其配對非常複雜,並且內建 API 可能更高效,因為它們直接使用字串的內部表示。如有必要,請為上述 API 安裝 polyfill。
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-string.prototype.charat |
瀏覽器相容性
載入中…