skip to Main Content

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


  1. Chosen as BEST ANSWER

    We can accumulate the codepoint lengths:

    function* codepointIndices(s) {
        let i = 0;
        for (let c of s) {
            yield [i, c];
            i += c.length;
        }
    }
    

  2. Use Objet.entries and the spread operator on your string:

    const res = Object.entries([..."H🏁ello"]);
    console.log(res)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search