Yogesh Chauhan's Blog

Reverse a String in JavaScript

in JavaScript on September 18, 2020

These solutions are from JavaScript Notes for Professionals.

Solution 1


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

// "olleh"

Note: The above solution only works if does not contain surrogate pairs.

Solution 2: Using Spread operator


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

console.log(reverseString('hello')); // "olleh"

Solution 3: Make a function using a For loop


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

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to get user’s Browser and Operating Systems information using PHP?PHPSlider animation using CSS transform propertyCSSHigher Order Functions in JavaScript with ExamplesJavaScriptHow to add onclick event to html elements dynamically using JavaScript?JavaScriptIs there a CSS parent selector?CSSFULL OUTER JOIN in PostgresPostgresHow to clean up after a plugin uninstall in WordPress?WordPressHow to add and remove capabilities from a role in WordPress?WordPressPHP __construct() functionPHPPagination in CSS with multiple examplesCSSHow to get previous days or next days in PHP?PHPWhat are partials in SCSS (Sass)?SCSS