Sử dụng thuộc tính length của String để lấy số ký tự (UTF-16 code units).
Ví dụ
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Tutorialspoint Tutorials";
document.write("Độ dài: " + str.length); // 24
// Với Unicode (emoji, tiếng Việt)
console.log("😀".length); // 2 (surrogate pair)
console.log("Tiếng Việt".length); // 10
// Đếm ký tự thực (grapheme clusters) - cần Intl.Segmenter (ES2022)
[...new Intl.Segmenter().segment("😀")].length; // 1
</script>
</body>
</html>
Lưu ý quan trọng:
lengthtrả về số UTF-16 code units, không phải số ký tự hiển thị (graphemes).- Emoji, ký tự ngoài BMP (Supplementary Planes) chiếm 2 code units → length +2.
- Kết hợp ký tự (combining marks) cũng tăng length.
Đếm đúng số ký tự hiển thị (ES2022):
function graphemeLength(str) {
return [...new Intl.Segmenter().segment(str)].length;
}
graphemeLength("👨👩👧👦"); // 1 (1 family emoji)
graphemeLength("e\u0301"); // 1 (e + combining acute)
graphemeLength("abc"); // 3
Polyfill cho trình duyệt cũ:
// Gần đúng: đếm code points (không xử lý combining marks)
function codePointLength(str) {
return [...str].length; // Spread dùng iterator của string (code points)
}