JavaScript: Extending String to Have startsWith and endWith Functions

Here’s two prototype functions you can add to your JavaScript to give you “startsWith” and “endsWith” functions:

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}
 
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(str) {
        return this.slice(-str.length) == str;
    };
}

Hope this helps!

This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *