String.charAt()
ส่งคืน ตัวอักษรเดี่ยว ที่ตำแหน่ง (Index) ที่ระบุ Index เริ่มจาก 0 หาก Index ไม่ถูกต้อง คืน Empty String ''
ไวยากรณ์
string.charAt(index)
ตัวอย่าง 1
<html> <body> <p id="demo"></p> <script>
var str = 'TUTORIALSPOINT AND TUTORIX';
var result = str.charAt(9);
document.getElementById('demo').innerHTML = result;
</script> </body> </html>
ผลลัพธ์: p (Index 9 ของ 'TUTORIALSPOINT' คือ 'P' ตัวเล็ก)
ตัวอย่าง 2
<script>
var str = 'Tutorix is a best e-learning platform';
var result = str.charAt(11);
document.write(result); // a
</script>
เปรียบเทียบ: charAt() vs Bracket Notation []
| Feature | charAt(index) | str[index] |
|---|---|---|
| Index Out of Bounds | คืน '' | คืน undefined |
| รองรับ Unicode (Emoji) | ไม่ดี (UTF-16 Code Units) | ไม่ดี (UTF-16 Code Units) |
| Browser Support | ทุก Browser | IE8+ |