ใช้ property length ของ String หาจำนวนตัวอักษร (UTF-16 code units)
ตัวอย่าง
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script>
var str = new String("Tutorialspoint Tutorials");
document.write("Length of string: " + str.length); // 24
</script>
</body>
</html>
รายละเอียด length
- คืนจำนวน UTF-16 code units ไม่ใช่จำนวนตัวอักษรจริง (graphemes)
- Emoji และตัวอักษรบางภาษาใช้ 2 code units (surrogate pairs)
- Read-only property (เปลี่ยนค่าไม่ได้)
ตัวอย่าง Unicode
"hello".length; // 5 "😀".length; // 2 (emoji = surrogate pair) "👨👩👧👦".length; // 11 (family emoji = multiple code points) "mañana".length; // 6 (ñ = 1 code unit)
นับตัวอักษรจริง (Graphemes)
// ใช้ spread operator (ES6)
[..."😀"].length; // 1
[..."👨👩👧👦"].length; // 1 (แต่ browser รองรับต่างกัน)
// หรือใช้ Intl.Segmenter (ES2022)
new Intl.Segmenter().segment("👨👩👧👦").length; // ต้อง iterate