21

I want to loop through a string and I want to have both the index and the character at this index. I know I could use a simple for loop for this, but I thought some of the newer features of Javascript/Typescript might be more elegant, so I tried this:

for (const [i, character] of Object.entries('Hello Stackoverflow')) {
    console.log(i);
    console.log(typeof(i));
    console.log(character);
}

Amazingly this works, however even though i counts up, it is a string. So for example this doesn't work:

'other string'.charAt(i)

I'm new at Typescript, so my questions are:

  • Why is i a string and not a number?
  • Is there a simpler / more elegant way to do this?
3
  • i is a number. Commented Nov 12, 2019 at 10:18
  • 2
    i outputs '1' '2' and so on, and typeof(i) prints 'string' Commented Nov 12, 2019 at 10:21
  • Yeah, my bad, didn't realise that. Commented Nov 12, 2019 at 10:27

2 Answers 2

29

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Looks elegant however I get this error for const chars = [...text];: Type 'string' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.ts(2569)
"Type 'string' is not an array type or a string type" --- this looks awkward: what exactly your text is? @Vladtn
Changing target from es5 to es2015 or es6 fixes the issue, see stackoverflow.com/a/59662571/331719
10

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);
}

3 Comments

text.charAt could break unicode characters. Try with const text = '👨‍👩‍👧‍👦';
@bauke So what I would have done in plain Javascript anyway, thanks! :)
@Fels it's broken though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.