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
Iterators & Generators in TypeScript
Iterators and generators are powerful features in TypeScript (and JavaScript) that allow for the creation and manipulation of sequences of values in a lazy, efficient manner, in this article we shall give a detailed account of what these concepts are all about and how to implement them in TypeScript
3 min read
How to Perform String Interpolation in TypeScript?
String interpolation in TypeScript is defined as an expression that is used to evaluate string literals containing expressions. It replaces placeholders with evaluated results, allowing dynamic string generation from static text and variables, making it ideal for templating logic and enhancing code
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 Sort a Numerical String in TypeScript ?
To sort numerical string in TypeScript, we could use localCompare method or convert numerical string to number. Below are the approaches used to sort numerical string in TypeScript: Table of Content Using localeCompareConverting to Numbers before sortingApproach 1: Using localeCompareThe localeCompa
2 min read
How to Create Array of String in TypeScript ?
An array of strings in TypeScript is a collection that can store multiple string values in a single variable, enabling efficient manipulation and access. Arrays can be created using array literals or the Array constructor, allowing dynamic and static initialization of string collections. We can decl
3 min read