Javascript String reverseIt()

Description

Javascript String reverseIt()


//Just like you can add methods to your own constructor, you can also add methods and properties to built in classes in JavaScript like Arrays and Objects.

//Add a reverse method to the String 'class' so that every instance of String can call reverse and reverse itself.
  
String.prototype.reverseIt = function() {
    var temp = [];
    for (var i = 0; i < this.length + 1; i++) {
        temp.push(this.charAt(this.length - i));
    }//from  w  w  w  .  j a va  2  s  .c o  m
    return temp.join("");
};

var myString = "hello";
myString.reverseIt();

Javascript String reverseIt()

String.prototype.reverseIt = function(){
 // this key word world be the string
 // note that all stings in the webpage auto
 // get the String JS abject.
 
 var newRev = '', i;
 for(i = this.length; i>=0; i--){
  newRev += this.substr(i, 1);/*from   w  ww.  j av a2s.c  om*/
 }
 return newRev;
};



PreviousNext

Related