Reverse a String in TypeScript
Last Updated :
24 Apr, 2025
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.
Method 1: Using a Loop
This 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
function reverseStringUsingLoop(str: string): string {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
const reversedStringLoop =
reverseStringUsingLoop('Geeks For Geeks');
console.log(reversedStringLoop);
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
function reverseStringUsingArray(str: string): string {
// Convert the string to an array
// of characters, reverse it,
//and join back to a string
return str.split('').reverse().join('');
}
const reversedStringLoop =
reverseStringUsingArray('Geeks For Geeks');
console.log(reversedStringLoop);