How to use the spread operator In Typescript
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;
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
Iterate Over Characters of a String in TypeScript
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.
Table of Content
- Example:
- Using for Loop
- Using for…of Loop
- Using split() Method
- Using forEach Method with split()
- Using the spread operator
- Using Array.from() Method
- Using while loop and charAt
Contact Us