3 Ways to Reverse a Given String in Javascript

Last updated on June 22, 2022 Napoleon Loading... Post a comment

The three examples below show you three different approaches to reverse a given string in Javascript. Without any further ado, let’s get started.

Using Array.reverse() method

The code with explanations:

 function reverseString(input){
        // turn the given string into an array
        var arr = input.split('');
        
        // reverse the array
        var reversedArr = arr.reverse();

        // turn the reversed array to a string
        var reversedString = reversedArr.join('');

        // return the result
        return reverseString;
}

// try it
console.log(reverseString('ABCD'));
console.log(reverseString('Welcome to KindaCode.com'));

Console output:

DCBA
moc.edoCadniK ot emocleW

You can shorten the reverseString() function above like so:

function reverseString(input) {
      return input.split('').reverse().join('');
}

Using a For loop

The code with explanations:

function reverseString(input) {
        // Create an empty string
        var reversedString = '';

        // Loop through the given string in descending order
        // and add each character to the reversedString variable
        for (var i = input.length - 1; i >= 0; i--) {
                reversedString += input[i];
        }

        // return the result
        return reversedString;
}

// try it
console.log(reverseString('12345'));
console.log(reverseString('Welcome to KindaCode.com'));

Output:

54321
moc.edoCadniK ot emocleW

Using Array.reduce() method

Knowing more than one way to solve a problem can help you understand Javascript better and deeper. Let’s have a look at the alternative for the two mentioned earlier:

function reverseString(str) {
    return Array.from(str)
           .reduce((result, character) => character + result, '');
}

// try it
console.log(reverseString('ABC123'));
console.log(reverseString('Learn Javascript with KindaCode.com'));

Output:

321CBA
(index):21 moc.edoCadniK htiw tpircsavaJ nraeL

Conclusion

We’ve covered the easiest and most intuitive solutions to reverse a given string with vanilla Javascript. However, there are other possible techniques to get the job done. If you would like to explore more new and exciting stuff about modern Javascript, take a look at the following articles:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles