Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript loop through string with index and value

Tags:

People also ask

How can we iterate through individual words in a string in JavaScript?

Simple for loop can use for in iterate through words in a string JavaScript. And for iterate words in string use split, map, and join methods (functions).

How do I traverse a string in JavaScript?

Javascript String @@iterator Method. String [@@iterator]( ) Method is used to make String iterable. [@@iterator]() returns iterator object which iterate over all code point of String. String[@@iterator] is Built – in Property of String.


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?