Open In App

How to Iterate Over Characters of a String in TypeScript ?

In Typescript, iterating over the characters of the string can be done using various approaches. We can use loops, split() method approach to iterate over the characters.

Below are the possible approaches:

Using for Loop

In this approach, we are using a for loop to iterate over a string’s characters by indexing each character based on the length of the string and accessing characters at each index.

Syntax:

for (initialization; condition; increment/decrement) {
// code
}

Example: Below is the implementation of the above-discussed approach.

let inputStr: string = "GeeksforGeeks";
for (let i = 0; i < inputStr.length; i++) {
    console.log(inputStr[i]);
}

Output:

G
e
e
k
s
f
o
r
G
e
e
k
s

Using forEach() method

In this approach, we are using the forEach() method on an array which is created from the string to iterate through characters separately.

Syntax:

array.forEach((element: ElementType, index: number, array: ArrayType) => {
// code
});

Example: Below is the implementation of the above-discussed approach.

let inputStr: string = "GeeksforGeeks";
Array.from(inputStr).forEach(char => {
    console.log(char);
});

Output:

G
e
e
k
s
f
o
r
G
e
e
k
s

Using split() method

In this approach, we Split the string into an array of characters using the split() method, then iterate through the array to process each character separately.

Syntax:

let arrayFromSplit: string[] = stringToSplit.split(separator, limit);

Example: Below is the implementation of the above-discussed approach.

let inputStr: string = "GeeksforGeeks";
inputStr.split('').forEach(char => {
    console.log(char);
});

Output:

G
e
e
k
s
f
o
r
G
e
e
k
s

Using for...of Loop

In this approach, we leverage the for...of loop in TypeScript to iterate directly over the characters of the string without the need for explicit indexing or converting the string into an array.

Syntax:

for (const char of inputStr) {
// code
}

Example: Below is the implementation of the above-discussed approach.

let inputStr: string = "GeeksforGeeks";
for (const char of inputStr) {
    console.log(char);
}

Output:

G
e
e
k
s
f
o
r
G
e
e
k
s
Article Tags :