เมธอด charCodeAt() คืนค่าตัวเลขที่บ่งชี้ค่า Unicode ของตัวอักษรที่ดัชนี (index) ที่กำหนด Unicode code points อยู่ในช่วง 0 ถึง 1,114,111 (0x10FFFF) 128 ค่าแรกตรงกับ ASCII encoding โดยตรง
พารามิเตอร์: charCodeAt(index)
- index — จำนวนเต็ม 0 ถึง (ความยาวสตริง - 1) หากไม่ระบุ จะเป็น 0
ตัวอย่าง
ลองรันโค้ดด้านล่างเพื่อคืนค่าตัวเลข Unicode ของตัวอักษร:
<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script>
var str = new String( "This is string" );
document.write("str.charCodeAt(0) is:" + str.charCodeAt(0));
document.write("<br />str.charCodeAt(1) is:" + str.charCodeAt(1));
document.write("<br />str.charCodeAt(2) is:" + str.charCodeAt(2));
document.write("<br />str.charCodeAt(3) is:" + str.charCodeAt(3));
document.write("<br />str.charCodeAt(4) is:" + str.charCodeAt(4));
document.write("<br />str.charCodeAt(5) is:" + str.charCodeAt(5));
</script>
</body>
</html>
ผลลัพธ์: T=84, h=104, i=105, s=115, (space)=32, i=105 ข้อจำกัด: charCodeAt() คืนค่า UTF-16 code unit (0-65535) สำหรับ Supplementary Characters (Emoji, ตัวอักษหายาก) จะคืน Surrogate Pair แยกกัน ควรใช้ codePointAt() (ES2015+) ที่คืน Code Point จริง (0-0x10FFFF)