Thursday, 3 November 2016

How to reverse a string using javascript?

Hi Guys very simple to print your name reverse order using java script.

Method 1 : Decrementing Decrementing for-loop with concatenation

   var name = 'ashokkumar';

var newname="";
for(var i=name.length-1; i>=0; i--)
{
newname + = name[i];
}

document.write(newname);

Output:
                 ramukkohsa

Method 2 : Incrementing for-loop with charAt

               var name = 'ashokkumar';

                var newname="";
for(var i=name.length-1;i>=0;i--)
{
newname= newname+name.charAt(i);
}
                document.write(newname);

Output :
                 ramukkohsa

Method 3 : Incrementing/decrementing for-loop with two arrays

         function reverse(s) {
                var newname = [];
                for (var i = s.length - 1, j = 0; i >= 0; i--, j++)
               newname [j] = s[i];
                return newname .join('');

         }

document.write(reverse('ashokkumar'));

Output :
            ramukkohsa

Method 4 : Incrementing for-loop with array pushing and charAt

   function reverse(s){
var newname = [];
for(var i=0,len=s.length;i<=len;i++)
{
newname.push(s.charAt(len-i));
}
return newname.join('');
}

document.write(reverse('ashokkumar'));

Output :

                ramukkohsa

Method 5 : In-Build functions

          function reverse(s){

               return s.split('').reverse().join('');
           }

       document.write(reverse('ashokkumar'));

Output :
              raamukkoshsa

Method 6 : Decrementing while-loop with concatenation and substring