This will be a short one
In ES6 strings are by default iterable with a for/of loop character-by-character. When iterating over strings, they are iterated by the Unicode codepoint, not by UTF-16 characters.
This can leave room for unexpected behavior. Let's look at this string for example: "I๐งก๐".
let str = "I๐งก๐";
console.log(str.length); // => 5
for (let char of str) {
console.log(char); // => "I", "๐งก", "๐"
}
This string has a .length
of 5 because the two emojis require each two UTF-16 characters to represent. But when you iterate over them with a for/of
loop, the loop body will run three times, once for each codepoint "I", "๐งก", "๐".
Top comments (0)