charCodeAt 方法回傳字串中指定位置字元的 Unicode 編碼。語法:
str_object.charCodeAt( x )
提示:字串的索引從 0 開始計算。
<script language="JavaScript"> document.write( "cnblogs".charCodeAt( 1 ) ); </script>
輸出:
110
110 是小寫 n 的 Unicode 編碼。
若 x 超出有效範圍,回傳 NaN。
console.log("abc".charCodeAt(0)); // 97
console.log("abc".charCodeAt(2)); // 99
console.log("abc".charCodeAt(3)); // NaN —— 越界
console.log("abc".charCodeAt(-1)); // NaN —— 負數這裡有個容易忽略的行為差異:charAt 越界回傳空字串,charCodeAt 越界回傳 NaN。兩者都不會丟出錯誤,因此若程式碼依賴回傳值做運算,NaN 會悄悄污染後續結果。
兩個方法極為相似,差別只在回傳的東西:
| 方法 | 回傳 | 越界時 |
|---|---|---|
| charAt(x) | 位於該位置的字元 | 空字串 "" |
| charCodeAt(x) | 該字元的編碼 | NaN |
console.log("A".charAt(0)); // "A"
console.log("A".charCodeAt(0)); // 65反方向的轉換用 String.fromCharCode()。
| 編碼 | 字元 |
|---|---|
| 48 – 57 | 0 – 9 |
| 65 – 90 | A – Z |
| 97 – 122 | a – z |
| 32 | 空白 |
| 13 | Enter |
function isDigit(ch) {
var code = ch.charCodeAt(0);
return code >= 48 && code <= 57;
}function compareChar(a, b) {
return a.charCodeAt(0) - b.charCodeAt(0);
}function shiftChar(ch, n) {
return String.fromCharCode(ch.charCodeAt(0) + n);
}
console.log(shiftChar("a", 1)); // "b"charCodeAt 回傳的是 UTF-16 碼元,而非完整的 Unicode 碼位。對於超出基本多文種平面的字元(emoji、部分罕用漢字),它只會給出代理對的一半:
var s = "😀"; console.log(s.length); // 2 —— 佔兩個碼元 console.log(s.charCodeAt(0).toString(16)); // "d83d" —— 高位代理 console.log(s.charCodeAt(1).toString(16)); // "de00" —— 低位代理 // ES6 的 codePointAt 取得完整碼位 console.log(s.codePointAt(0).toString(16)); // "1f600"
要正確走訪含 emoji 的字串,用 for...of 或展開語法,它們以碼位為單位:
for (var ch of "a😀b") {
console.log(ch, ch.codePointAt(0).toString(16));
}
// a 61
// 😀 1f600
// b 62/\d/.test(ch)、/[a-z]/.test(ch)。