JavaScript string startsWith 

Joined:
02/21/2009
Posts:
151

August 09, 2009 03:57:04    Last update: August 09, 2009 03:57:04
Contrary to some online documentation, JavaScript does not seem to support the functions startsWith, endsWith etc. This snippet adds these functions.

String.prototype.endsWith = function (a) {
    return this.substr(this.length - a.length) === a;
}

String.prototype.startsWith = function (a) {
    return this.substr(0, a.length) === a;
}

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

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

String.prototype.trim = function() {
    return this.replace(/^\s*/, '').replace(/\s*$/, '');
}
Share |
| Comment  | Tags