Iterate over a String with Index in TypeScript

avatar

Borislav Hadzhiev

Wed Feb 16 20222 min read

banner

Photo by Joshua Earle

Iterate over a String with Index in TypeScript #

To iterate over a string with index:

  1. Use the spread syntax (...) to unpack the string into an array.
  2. Use the forEach() method to iterate over the array.
  3. The second parameter the forEach() method takes is the index of the current element.
index.ts
const str = 'hello'; const arr: string[] = [...str]; console.log(arr); // 👉️ ['h', 'e', 'l', 'l', 'o'] arr.forEach((char, index) => { // 👇️ h 0, e 1, l 2, l 3, o 4 console.log(char, index); });

We used the spread syntax (...) to unpack the string into an array.

The array contains all of the characters in the string as elements.

The function we passed to the Array.forEach method gets called with each element in the array.

The callback function gets passed the following 3 parameters:

  1. The current element in the array.
  2. The index of the element in the array.
  3. The array on which we called the forEach() method.

The forEach method returns undefined, so it is used to mutate an external variable.

An important thing to note when using the forEach() method is - you can't use the break keyword to break out of the loop.

If you have to use the break keyword to break out of the loop if a condition is met, use a basic for loop instead.

index.ts
const str = 'hello'; for (let index = 0; index < str.length; index++) { // 👇️ h 0, e 1, l 2 console.log(str[index], index); if (index === 2) { break; } }

The break keyword enables us to exit the loop early and is not supported when using the forEach() method.

Other than that, the for loop is a little more verbose and is used less often in the real world as the language offers more and more abstractions on top of it.

Use the search field on my Home Page to filter through my more than 1,000 articles.