How can one iterate over the indices of codepoints and their values in a JavaScript string?
For example, [...codepointIndices("H🏁ello")]
should output:
[[0, "H"], [1, "🏁"], [3, "e"], [4, "l"], [5, "l"], [6, "o"]]
One can iterate over codepoints in JavaScript with String.prototype[Symbol.iterator]
, but there does not appear to be an in-built way to include the indices of each codepoint.
2
Answers
We can accumulate the codepoint lengths:
Use Objet.entries and the spread operator on your string: