![]() |
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 Method 1: Using a LoopThis method utilizes a loop to iterate through the characters of the string in reverse order, building the reversed string. It is a more traditional approach and may be preferred in scenarios where simplicity and explicit control over the iteration are desired. Example: In this example, a string “Geeks For Geeks” and is reversed using the a loop. Javascript
Output: skeeG roF skeeG
Method 2: Using Array Methods (reverse,split and join)This method leverages the array functions split, reverse, and join to convert the string into an array of characters, reverse the array, and then join it back into a string. It is a concise and readable approach that takes advantage of the built-in array methods. Example: In this example, a string “Geeks For Geeks” and is reversed using the array methods. Javascript
Output: skeeG roF skeeG
Method 3: Using reduceThis method employs the reduce function to accumulate the reversed string. It iterates through the characters of the string, prepending each character to the accumulating reversed string. Example: In this example, a string “Geeks For Geeks” and is reversed using the reduce method. Javascript
Output: skeeG roF skeeG
|
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |