
if (!String.prototype.lastIndexOf) {
    String.prototype.lastIndexOf =  function(c) {
        var i = this.length + 1;
        var rv = -1;
        if (arguments[1] != null) {
           i = arguments[1] + 1;
        }
        while (--i >= 0) {
            if (this.substr(i, 1) == c) {
                rv = --i;
                break;
            }
        }
        return rv;
    }
}

String.prototype.stripLeft = function() {
    return this.replace(/^\s+/, '');
}

String.prototype.stripRight = function() {
    return this.replace(/\s+$/, '');
}

String.prototype.strip = function() {
    return this.stripLeft().stripRight();
}

String.prototype.words = function() {
    /*
        s.words()
            Returns an array of the words in the string.
            
        s.words(n)
            Returns the n-th word of the string.
    */
    var rv = this.strip().split(/\s+/);
    if (arguments.length != 0) {
        rv = rv[arguments[0]];
    }
    return rv;
}

String.prototype.contains = function(s) {
  if (s.constructor == Array){
    return s.every(this.contains, this);
  }
  return (this.indexOf(s) != -1);
}

String.prototype.startsWith = function(s) {
    return (this.indexOf(s) == 0);
}

String.prototype.endsWith = function(s) {
    return (this.lastIndexOf(s) != -1 && this.lastIndexOf(s) + s.length == this.length);
}

String.prototype.removeEnding = function(x) {
    /*
        s.removeEnding('string')
           Removes a string from the end of s.
           
        s.removeEnding(<number>)
            Removes <number> characters from the end of s.
    */
    if (typeof x == 'number') {
        return this.substr(0, this.length - x);
    }
    else if (this.endsWith(x)) {
        return this.substr(0, this.length - x.length);
    }
    else {
        return this;
    }
}

String.prototype.removePunctuation = function() {
  return this.replace(/[.,;:?]/g, ' ')
}

String.prototype.forEach = function (f, obj) {
	var l = this.length;	// must be fixed during loop... see docs
	for (var i = 0; i < l; i++) {
	    f.call(obj, this.charAt(i), i, this);
	}
};

String.prototype.rot13 = function() {
  var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var convertedAlphabet = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM";
  var rv = "";
  this.forEach(function(chr) {
    if (alphabet.contains(chr)) {
      rv += convertedAlphabet.charAt(alphabet.indexOf(chr));
    }
    else {
      rv += chr;
    }
  });
  return rv;
}

String.prototype.capitalise = function() {
  return this.replace(/\w+/g, function(a) {
    return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
  });
};
