Javascript Reverse String
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');
Output
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.
Custom reverse() function
function reverse(string) {
var strRev = "";
for (var i = string.length - 1; i >= 0; i--) {
strRev += string[i];
}
return strRev;
}
reverse("zebra");
Output
Using spread operator
function reverseString(str) {
return [...String(str)].reverse().join('');
}
console.log(reverseString('stackoverflow'));