How do I determine the width of the result of codePointAt?

Viewed 235

I'm trying to loop over the Unicode characters in a Javascript string, that I assume is encoded with UTF-16.

It is my understanding that UTF-16 is variable width. That is, a single Unicode character may be split across multiple 16-bit characters. I can use s[i].codePointAt to get the Unicode character beginning at a given code point. But once I have it, how do I know how far to advance i?

Roughly, what is getWidth here? Is it simply c > Math.pow(2, 16)?

for (var i = 0; i < s.length;) {
    var c = s.codePointAt(i);
    // do some operation with c
    i = i + getWidth(c)
}

Is there a standard library function I can use to determine how far to advance? Or a way to iterate over the Unicode code points in a string?

4 Answers
Related