YogeshChauhan . com

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"
amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Accessing and Setting features of JavaScript ObjectsJavaScript3 Types of Arrays in PHPPHPClasses in JavaScript: The BasicsJavaScriptWhere is the PHP log file located on Mac OS?PHPJavaScript: Methods for HTML DOM classList PropertyJavaScriptLEFT JOIN in PostgresPostgresThe Drupal flowDrupalFunction Scope in JavaScript for BeginnersJavaScriptWhat is Host Hardening and What are some Important Hardening Steps?Misc2 Ways we can create an Array in JavaScriptJavaScriptHow to Use SQL MAX() Function with Dates?SQL/MySQLWhy it’s not a good idea to create Number objects in JavaScript?JavaScript