Typescript loop through string with index and value

The unicode-safe way would be to split to characters using spread syntax:

const chars = [...text];

Then you iterate using good old Array.prototype.forEach

chars.forEach((c, i) => console.log(c, i));

Why is i a string and not a number?

Because Object.entries() returns a key-value pair and is intended to be used for objects, where keys are of course strings.

Is there a simpler / more elegant way to do this?

Just a simple for loop with charAt(i) can do the trick:

const text = 'Hello StackOverflow';
for (let i = 0; i < text.length; i++) {
  const character = text.charAt(i);
  console.log(i, character);
}

Tags:

Typescript