MOCKSTACKS
EN
Questions And Answers

More Tutorials









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

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.


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

arbez

Using spread operator


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

Output

"wolfrevokcats"


Conclusion

In this page (written and validated by ) you learned about Javascript Reverse String . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Comparing Strings.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.