Iterate Over Characters of a String in TypeScript
Last Updated :
25 Jun, 2024
Iterating over characters of a string involves going through them one by one using loops or specific methods. This is useful for tasks like changing or analyzing the content of a string efficiently.
Example:
Input: string = "Hello Geeks";
Output:
H
e
l
l
o
G
e
e
k
s
Below listed methods can be used to iterate over characters of a string in TypeScript.
Using for Loop
The for-loop syntax is straightforward. It iterates over each character in the string by accessing the characters using the string's index.
Syntax:
for (statement 1 ; statement 2 ; statement 3){
//code here
};
Example: The below code implements the for loop to iterate over characters of a string.
JavaScript
type CharIterator = (str: string) => void;
const iterateOverCharacters: CharIterator = (str) => {
for (let i = 0; i < str.length; i++) {
const char: string = str[i];
console.log(char);
}
};
const myString: string = "GeeksforGeeks";
iterateOverCharacters(myString);
Output:
G
e
e
k
s
f
o
r
G
e
e
k
s
Using for…of Loop
The for...of loop syntax allows direct iteration over each character in the string without needing to visit the index explicitly.
Syntax:
for ( variable of iterableObjectName) {
//code here
}
Example: The below code explains the use of for/of loop to iterate over string characters.
JavaScript
type CharIterator = (str: string) => void;
const iterateOverCharacters: CharIterator = (str) => {
for (const char of str) {
console.log(char);
}
};
const myString: string = "TypeScript";
iterateOverCharacters(myString);
Output:
T
y
p
e
S
c
r
i
p
t
Using split() Method
The split() method splits the string into array of characters, which can then be iterated over using a loop or array methods.
Syntax:
str.split('');
Example: The below code is practical implementation of the split() method to iterate over string characters.
JavaScript
type CharIterator = (str: string) => void;
const iterateOverCharacters: CharIterator = (str) => {
const chars: string[] = str.split('');
for (const char of chars) {
console.log(char);
}
};
const myString: string = "JavaScript";
iterateOverCharacters(myString);
Output:
J
a
v
a
S
c
r
i
p
t
Using forEach Method with split()
The forEach method can be used to iterate over the array returned by str.split(''). This method iterates over each element of the array and applies the provided function to each element.
Syntax:
array.forEach(()=>{});
JavaScript
type CharIterator = (str: string) => void;
const iterateOverCharacters: CharIterator = (str) => {
str.split('').forEach(char => {
console.log(char);
});
};
const myString: string = "Geeks";
iterateOverCharacters(myString);
Output:
G
e
e
k
s
Using the spread operator
The spread operator (...str) converts the string str into an array of individual characters, allowing each character to be iterated over and processed using the forEach method.
Syntax:
...operatingValue;
JavaScript
type CharIterator = (str: string) => void;
const iterateOverCharacters: CharIterator = (str) => {
[...str].forEach((char: string) => {
console.log(char);
});
};
const myString: string = "GFG";
iterateOverCharacters(myString);
Output:
G
F
G
Using Array.from() Method
The Array.from() method creates a new, shallow-copied array instance from an array-like or iterable object, such as a string. This allows for convenient iteration over the characters of the string.
Syntax:
Array.from(string).forEach((char: string) => {
// code
});
Example: Below is the implementation of the above-discussed approach.
JavaScript
type CharIterator = (str: string) => void;
const iterateOverCharacters: CharIterator = (str) => {
Array.from(str).forEach((char: string) => {
console.log(char);
});
};
const myString: string = "GFG";
iterateOverCharacters(myString);
Output:
G
F
G
Using while loop and charAt
In this approach we initialize the string str. We use a while loop to iterate over each character. The loop runs as long as i is less than the length of the string. Inside the loop, we use str.charAt(i) to get the character at the current index i. We increment i after each iteration to move to the next character.
Example: Below is the implementation of the above-discussed approach.
JavaScript
let str: string = "GFG";
let i: number = 0;
while (i < str.length) {
console.log(str.charAt(i));
i++;
}
Output:
G
F
G
Using String.prototype.replace Method
The String.prototype.replace method can be used with a regular expression to iterate over each character of the string by providing a function to process each match (i.e., each character).
Syntax:
str.replace(/./g, (char) => {
// code to process each character
});
Example: The below code demonstrates how to use the replace method to iterate over the characters of a string and log each character to the console.
JavaScript
type CharIterator = (str: string) => void;
const iterateOverCharacters: CharIterator = (str) => {
str.replace(/./g, (char) => {
console.log(char);
return char;
});
};
const myString: string = "HelloGeeks";
iterateOverCharacters(myString);
Output:
H
e
l
l
o
G
e
e
k
s
Similar Reads
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: Table of Content Using for LoopUsing forEach() methodUsing split() methodUsing for...of LoopUs
2 min read
Delete First Character of a String in TypeScript
Deleting the first character of a string in Typescript consists of removing the character at the 0th index of the string. Using various inbuilt methods, we can extract the first character of the input string and print or return only the remaining characters apart from the first character. There are
2 min read
How to Iterate Over Characters of a String in JavaScript ?
There are several methods to iterate over characters of a string in JavaScript. 1. Using for LoopThe classic for loop is one of the most common ways to iterate over a string. Here, we loop through the string by indexing each character based on the string's length. Syntax for (statement 1 ; statement
2 min read
Reverse a String in TypeScript
Reversing a string involves changing the order of its characters, so the last character becomes the first, and vice versa. In TypeScript, there are various methods to achieve this, depending on the developer's preference and the specific requirements of the task. Table of Content Using a LoopUsing A
2 min read
TypeScript String charAt() Method
The String.prototype.charAt() method in TypeScript is used to return the character at the specified index of a string. The characters in the string are indexed from left to right, starting at 0. Syntax: string.charAt( index )Parameter: This method accepts a single parameter as mentioned above and de
2 min read
TypeScript String charCodeAt() Method
The String.charCodeAt() method in TypeScript returns the Unicode value of the character at a specified index in a string. It takes an integer index as a parameter and returns the corresponding Unicode value as a number. Syntaxstring.charCodeAt(index);Parameter: This method accepts a single parameter
2 min read
How to Iterate over Map Elements in TypeScript ?
In TypeScript, iterating over the Map elements means accessing and traversing over the key-value pairs of the Map Data Structure. The Map is nothing but the iterative interface in TypeScript. We can iterate over the Map elements in TypeScript using various approaches that include inbuilt methods and
4 min read
TypeScript Interview Questions and Answers
TypeScript, a robust, statically typed superset of JavaScript, has become a go-to language for building scalable and maintainable applications. Developed by Microsoft, it enhances JavaScript by adding static typing and modern ECMAScript features, enabling developers to catch errors early and improve
15+ min read
How to Iterate Over Object Properties in TypeScript
In TypeScript, Objects are the fundamental data structures that use key-value pair structures to store the data efficiently. To iterate over them is a common task for manipulating or accessing the stored data. TypeScript is a superset of JavaScript and provides several ways to iterate over object pr
3 min read
TypeScript String.fromCharCode() Method
The fromCharCode() is an inbuilt TypeScript String method. It mainly changes Unicode code points within the Basic Multilingual Plane (BMP) into strings. Although it provides a method for dealing with characters through typing on a keyboard it has restrictions when it comes to characters, outside the
1 min read