JavaScript Reverse String


Example

The most "popular" way of reversing a string in JavaScript is the following code fragment, which is quite common:

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

reverseString('string');    // "gnirts"

However, this will work only so long as the string being reversed does not contain surrogate pairs. Astral symbols, i.e. characters outside of the basic multilingual plane, may be represented by two code units, and will lead this naive technique to produce wrong results. Moreover, characters with combining marks (e.g. diaeresis) will appear on the logical "next" character instead of the original one it was combined with.

'𝌆■.'.split('').reverse().join(''); //fails

While the method will work fine for most languages, a truly accurate, encoding respecting algorithm for string reversal is slightly more involved. One such implementation is a tiny library called Esrever, which uses regular expressions for matching combining marks and surrogate pairs in order to perform the reversing perfectly.

Explanation

SectionExplanationResult
strThe input string"string"
String.prototype.split( deliminator )Splits string str into an array. The parameter "" means to split between each character.["s","t","r","i","n","g"]
Array.prototype.reverse()Returns the array from the split string with its elements in reverse order.["g","n","i","r","t","s"]
Array.prototype.join( deliminator )Joins the elements in the array together into a string. The "" parameter means an empty deliminator (i.e., the elements of the array are put right next to each other)."gnirts"

Using spread operator

6
function reverseString(str) {
    return [...String(str)].reverse().join('');    
}

console.log(reverseString('stackoverflow'));  // "wolfrevokcats"
console.log(reverseString(1337));             // "7331"
console.log(reverseString([1, 2, 3]));        // "3,2,1"

Custom reverse() function

function reverse(string) {
    var strRev = "";
    for (var i = string.length - 1; i >= 0; i--) {
        strRev += string[i];
    }
    return strRev; 
}

reverse("zebra");  // "arbez"