charCodeAt() 會傳回指定索引處字元的 Unicode 編碼。若索引超出範圍,會傳回 NaN。
string.charCodeAt(index)
index 可省略,預設為 0。傳回值為數字,代表該位置的 UTF-16 編碼單元。
const str = new String('This is string');
console.log(str.charCodeAt(0));
console.log(str.charCodeAt(1));
console.log(str.charCodeAt(4));
輸出分別為 84、104 與 32。這個方法常用於檢查字元編碼、實作簡單字串處理或進行編碼轉換。