Open In App

Reverse a String in TypeScript

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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);


Output:

skeeG roF skeeG

Method 3: Using reduce

This 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




function reverseStringUsingReduce(str: string): string {
  // using reduce with split functions
    return str.split('')
        .reduce((reversed, char) => char + reversed, '');
}
 
const reversedStringReduce =
    reverseStringUsingReduce('Geeks For Geeks');
console.log(reversedStringReduce);


Output:

skeeG roF skeeG


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads