How to Reverse a String in TypeScript?

In one of my recent TypeScript applications, I had to reverse a string where we were generating custom tracking codes. Each code had to be displayed in reverse for security reasons before sending it to the frontend.

While searching for solutions, I came across different methods to reverse a string in TypeScript, such as split, reverse, join, and reusable utility functions.

In this TypeScript tutorial, I will explain how to reverse strings in TypeScript using various methods and examples.

Reverse a String in TypeScript

In the examples below, we will discuss various methods through which we can efficiently reverse sitting values in TypeScript.

Method 1: Using the split-reverse-join Approach

The most common way to reverse a string in TypeScript is by using JavaScript’s built-in array methods. This is my go-to approach for most projects:

function reverseString(str: string): string {
    return str.split('').reverse().join('');
}

// Example
const original = "TypeScript";
const reversed = reverseString(original);
console.log(reversed); // "tpircSepyT"

Output:

Reverse String in TypeScript

Here’s what’s happening in this function:

  1. split(”) converts the string into an array of individual characters.
  2. reverse() reverses the order of the array elements.
  3. join(”) combines the array back into a string.

This method is efficient and works well for most use cases. It’s also very readable, making it a great choice for team projects where code clarity is important.

Check out: Convert a String to Lowercase in TypeScript

Method 2: Using a For Loop

Sometimes, I prefer a more explicit approach, especially when working on performance-critical applications. A traditional for loop gives you more control:

function reverseStringWithLoop(str: string): string {
    let reversed = '';
    for (let i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
    }
    return reversed;
}

// Example
const stateName = "California";
console.log(reverseStringWithLoop(stateName)); // "ainrofilaC"

Output:

TypeScript Reverse a String

This method iterates through the string from the end to the beginning, building a new string character by character. While slightly more verbose, it can be more efficient for very long strings as it avoids creating intermediate arrays.

Check out: Check if a String is Null or Empty in TypeScript

Method 3: Using Array Reduce

For a more functional programming approach, we can use the array reduce method:

function reverseStringWithReduce(str: string): string {
    return str.split('').reduce((reversed, character) => {
        return character + reversed;
    }, '');
}

// Example
const cityName = "New York";
console.log(reverseStringWithReduce(cityName)); // "kroY weN"

Output:

Use Array Reduce to Reverse string in TypeScript

This method works by:

  1. Converting the string to an array of characters
  2. Using reduce to build a new string by prepending each character to our result
  3. Starting with an empty string as the initial value

I find this approach particularly elegant when working within a codebase that already uses a functional programming style.

Check out: Replace Characters in a String Using TypeScript

Method 4: Using TypeScript Generics for More Flexibility

If you want to create a more reusable solution, you can leverage TypeScript’s type system with generics:

function reverse<T>(input: T[]): T[] {
    return [...input].reverse();
}

// For strings specifically
function reverseStringGeneric(str: string): string {
    return reverse(str.split('')).join('');
}

// Examples
const usState = "Texas";
console.log(reverseStringGeneric(usState)); // "saxeT"

// The generic function can also be used with other array types
const numbers = [1, 2, 3, 4, 5];
console.log(reverse(numbers)); // [5, 4, 3, 2, 1]

Output:

Reverse TypeScript String using Generics

This approach creates a generic reverse function that works with any array type, not just strings. It’s a great example of how TypeScript’s type system can make your code more versatile and reusable.

Check out: Convert an Array to a String in TypeScript

Handling Special Cases: Unicode and Emojis

When working with international text or modern communications that include emojis, you need to be careful with string reversal. Some characters in Unicode consist of multiple code points:

function reverseUnicodeString(str: string): string {
    return [...str].reverse().join('');
}

// Example with emoji
const withEmoji = "Hello 👋 World";
console.log(reverseString(withEmoji));       // Often incorrect with emojis
console.log(reverseUnicodeString(withEmoji)); // Correctly handles emojis

Output:

Special case to reverse string in TypeScript

The spread operator (…) in this function properly handles Unicode characters, including emojis and combining marks, by splitting the string into an array of Unicode characters rather than UTF-16 code units.

Check out: Convert String to Number in TypeScript

Performance Considerations

In my experience working on enterprise TypeScript applications, I’ve found that for most use cases, the choice of string reversal method doesn’t significantly impact performance. However, for applications that process large volumes of text:

  • The split-reverse-join method is generally fast and clear
  • The for loop approach can be slightly more efficient for very long strings
  • The reduce method may be slightly less performant but offers better integration with functional code

I’ve found that the split-reverse-join method strikes the best balance between readability and performance for most applications I’ve worked on.

String reversal is a common operation in TypeScript development, and having these different techniques in your toolkit gives you flexibility for various scenarios. Whether you’re building a text editor, processing user input, or working with data transformations, these methods will serve you well.

Remember that the best approach often depends on your specific use case, your project’s coding standards, and how the reversed strings will be used in your application.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.