How to use split() Method In Typescript
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.
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
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