• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

Reversing A String In Javascript 3 Different Ways

Fun, Javascript · July 31, 2015

Leading off from my previous post about swapping variable values, I thought I would write a follow-up post on how to reverse a string in Javascript. Surprisingly in Javascript there is no native means of reversing a string (I guess there are very few situations where you would need to do that).

This is not going to be an exercise in code golfing. In-fact, I am only going to show you 3 different ways to reverse a string (although there are potentially tens of different ways to do it). My preference is the first solution using Array.reverse, but pick whatever suits your needs.

This is not going to be about performance or doing the most terse code, this is just a fun little experiment where you might learn a new trick to add to your Javascript toolbox.

Array.reverse:
You’re probably thinking, wait I thought we were reversing a string, why are you using the Array.reverse method. Using the String.split method we are converting our string into an Array of characters. Then we are reversing the order of each value in the array and then finally we convert the Array back to a String using the Array.join method.

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

Decrementing while-loop:
Although pretty verbose, this solution does have its advantages over solution one. You’re not creating an array and you’re just concatenating a string based on characters from the source string.

From a performance perspective, this one would probably yield the best results (although untested). For extremely long strings, the performance gains might drop out the window though.

function reverseString(str) {
    var temp = '';
    var i = str.length;

    while (i > 0) {
        temp += str.substring(i - 1, i);
        i--;
    }


    return temp;
}
reverseString('dwayne');

Recursion
I love how simple and clear this solution is. You can clearly see that the String.charAt and String.substr methods are being used to pass through a different value by calling itself each time until the string is empty of which the ternary would just return an empty string instead of using recursion to call itself. This would probably yield the second best performance after the second solution.

function reverseString(str) {
    return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString('dwayne');

Got your own solution? Share it below in the comments

Dwayne

Leave a Reply Cancel reply

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Dave
Dave
7 years ago

10 different methods with performance tests:
https://jsperf.com/string-reverse-function-performance/6

Appears a for-loop over the string (as a char array) then concatenating to a new string yields the best performance, at least in Chrome:


// decrementing for-loop with concatenation
function reverse(s) {
var o = '';

for (var i = s.length - 1; i >= 0; i--)
o += s[i];

return o;
}

Amazingly, the most naive method performs best (as in, it’s probably the code you’d get from a naive programmer).

0
Hidayt Rahman
Hidayt Rahman
7 years ago

Dear Dwayne,

Nice concept !!

Is there any pre-defined function in JavaScript for do this thing easily?

Thanks

0
S.pachaiappan
S.pachaiappan
6 years ago

Dear Dwayne,

pls Explain reverse string without using reverse method() ?

Send for my mail ,pls ..
Waiting egerly for your positive reply….
thank you

0

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Waiting for an Element to Exist With JavaScript
  • Thoughts on the Flipper Zero
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • How To Paginate An Array In Javascript
  • How To Mock uuid In Jest
  • How to Copy Files Using the Copy Webpack Plugin (without copying the entire folder structure)
  • Reliably waiting for network responses in Playwright
  • Wild Natural Deodorant Review

Recent Comments

  • Dwayne on Is Asking Developers How to Write FizzBuzz Outdated?
  • kevmeister68 on Is Asking Developers How to Write FizzBuzz Outdated?
  • Kevmeister68 on Start-Ups and Companies That Embrace Work From Anywhere Will Be More Likely to Survive the Coming Recession in 2023
  • kevmeister68 on What Would Get People Back Into the Office?
  • Dwayne on PHP Will Not Die

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz