In this quick tutorial, we’re going to see how we can reverse a String in JavaScript .
We’ll start to do this processing using plain JavaScript first . Reverse a String is one of the most frequently asked JavaScript interview questions .
Furthermore, we’ll demonstrate how to reverse the order of words in a sentence. There are varierty of wasy to do this in javascript .Lets have a look at all the different ways .
Using JavaScript Built In Functions
One of the easiest way is to using a split function and then using the reverse() built in function and then concatening using join() method as below.
It is usually noob way if asked in interview . So avoid answering this in a interview.
function reverseString(input) {
return input.split('').reverse().join('');
}
Reverse a String In JavaScript Using Loop
Have a look at the most basic way of doing this by iterating the string in reverse order and then returning it .
function reverse(input) {
var ouPut = [];
//consider input ='TEST'
for (var i = input.length - 1, j = 0; i >= 0; i--, j++)
ouPut [j] = input[i];
return ouPut .join('');
}
Now with the given code where input="TEST"
. Have a look at how the code executes
Iteration Number | i | j | input[i] | outPut[j] | Result outPut[] |
First | 3 | 0 | T | T | [T] |
Second | 2 | 1 | S | S | [T,S] |
Third | 1 | 2 | E | E | [T,S,E] |
Fourth | 0 | 3 | T | T | [T,S,E,T] |
output.join(”) is the last line which joins the array and converts it as an String. Have a look at mozilla doc here on Array.join() .
Using Recursion to Reverse a String
We are going to use recursion to split first item using substr()
method and then add it to the end of the string.
function reverse(inpStr){
if(inpStr === ""){
return inpStr
}else{
return reverse(inpStr.substr(1)) + inpStr[0] }
}