且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript:将方法添加到字符串类

更新时间:2023-12-02 23:32:04

您可以扩展 String 原型;

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");

在这里查看JSFiddle