Javascript String Prototype Reverse Words

Description

Javascript String Prototype Reverse Words


String.prototype.reverseWords = function() {
  let resultString = "";
  if (this.length > 0) {
    let StringArr = this.split(" ");
    for (let i = StringArr.length-1; i > -1; i--) {
      resultString += StringArr[i];/*  w w w  . j  a  va2  s .c o m*/
      if (i > 0)
        resultString += " ";
    }
  }
  return resultString;
}

let StringObjectInstance = new String("This is a test of the String prototype.");
let StringPrimitiveInstance1 = "This is a test of the String prototype on a primitive.";
let StringPrimitiveInstance2 = String("This is a test of the String prototype on another kind of primitive.");

console.log(StringObjectInstance.reverseWords());
console.log(StringPrimitiveInstance1.reverseWords());
console.log(StringPrimitiveInstance2.reverseWords());
console.log("This is a test of the string primitive".reverseWords());



PreviousNext

Related