JavaScript String charCodeAt()
示例
獲取字串中第一個字元的 Unicode 值
let text = "HELLO WORLD";
let code = text.charCodeAt(0);
自己動手試一試 »
獲取第二個字元的 Unicode 值
let text = "HELLO WORLD";
let code = text.charCodeAt(1);
自己動手試一試 »
更多示例見下文。
描述
charCodeAt()
方法返回字串中指定索引(位置)處字元的 Unicode 值。
第一個字元的索引是 0,第二個是 1,依此類推。
最後一個字元的索引是字串長度 - 1(參見下面的示例)。
另請參閱 charAt()
方法。
charCodeAt() 與 codePointAt()
charCodeAt()
是 UTF-16,codePointAt()
是 Unicode。
charCodeAt()
返回一個介於 0 到 65535 之間的數字。
這兩種方法都返回一個表示字元 UTF-16 程式碼的整數,但只有 codePointAt()
能夠返回大於 0xFFFF (65535) 的 Unicode 值的完整值。
有關 Unicode 字元集的更多資訊,請訪問我們的 Unicode 參考手冊。
語法
string.charCodeAt(index)
引數
引數 | 描述 |
index | 可選。一個數字。 字元的索引(位置)。 預設值 = 0。 |
返回值
型別 | 描述 |
一個數字 | 指定索引處字元的 Unicode 值。 如果索引無效,則返回 NaN。 |
更多示例
獲取字串中最後一個字元的 Unicode 值
let text = "HELLO WORLD";
let code = text.charCodeAt(text.length-1);
自己動手試一試 »
獲取第 15 個字元的 Unicode 值
let text = "HELLO WORLD";
let code = text.charCodeAt(15);
自己動手試一試 »
瀏覽器支援
charCodeAt()
是 ECMAScript1 (ES1) 的特性。
ES1 (JavaScript 1997) 在所有瀏覽器中都得到完全支援
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 是 |