The length
property of strings in JavaScript is the number of code units, for example:
console.log("a".length); // 3
I have implemented a function that returns the number of Unicode points:
function length(str) {
let l = 0;
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code >= 0xD800 && code <= 0xDBFF)
i++;
l += 1;
}
return l;
}
console.log(length("a")); // 2
However, if the string is very long, my implementation is not very effective. Does anyone have a better implementation? Why does not the ECMAScript provide a built-in method doing this job?