You are currently viewing Reversing a String

Reversing a String

Sometimes you want to reverse a string, say from “Hello” to “olleH” (without the quotes).  Just how do you do it?  It can be done easily with JavaScript, and I will show you two ways.

Method 1:

This method uses the more traditional method.  It determines the length of the string (input.length) then loops to add each character found in the beginning of the output string, hence creating a reverse effect.

var input = "hello";
var out = "";

for (var i=0; i < input.length; i++) {
out = input.charAt(i) + out;
}
document.write( out );

 

Method 2:

This method uses the built-in function in JavaScript, obviously it splits the input string (comma separated), use the reverse function to reverse the order, and join them together (dropping the commas).

var input = "hello";
var out = "";

document.write( input.split("").reverse().join("") );

 

Either method obviously works fine, I personally prefer the second method since it uses JavaScript’s built-in function instead of using a loop.  We all know having a loop (of any repetitions) costs computer memory resources and I try to avoid it as much as I can.