Add method to string class

You can extend the String prototype;

String.prototype.distance = function (char) {
    var index = this.indexOf(char);

    if (index === -1) {
        alert(char + " does not appear in " + this);
    } else {
        alert(char + " is " + (this.length - index) + " characters from the end of the string!");
    }
};

… and use it like this;

"Hello".distance("H");

See a JSFiddle here.

Leave a Comment