![]() |
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 LoopIn 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) { Example: Below is the implementation of the above-discussed approach.
Output: G Using forEach() methodIn 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) => { Example: Below is the implementation of the above-discussed approach.
Output:G Using split() methodIn 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.
Output:G Using for…of LoopIn 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) { Example: Below is the implementation of the above-discussed approach.
Output: G Using map() MethodIn this approach, we use the map() method on an array created from the string. Although map() is typically used for transforming elements, it can also be used for iteration. Syntax:array.map((element: ElementType, index: number, array: ArrayType) => { Example:
Output: G |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |