JavaScript Basic Algorithm Scripting – Reverse a String

There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.

Below are my three most interesting ways to solve the problem of reversing a string in JavaScript.

Reverse a String With Built-In Functions

the String.prototype.split() method,

the Array.prototype.reverse() method

and the Array.prototype.join() method.

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

Reverse a String With a Decrementing For Loop

function reverseString(str){
//Step 1. Create an empty string to store new string
var newString = "" ;
//Loop string str.length -1 which corresponds to the last character
for (var i= str.length  - 1; i >= 0 ; i--){
newString += str[i];
}
return newString;
}

Reverse a String With Recursion

the String.prototype.substr() method

and the String.prototype.charAt() method.

function reserseString(str){
if  (str === "")
return "";
else
return reserveString(str.substr(1)) + str.charAt(0);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s