I want my java.lang!

Missing those java.lang features that got left out of JavaScript? Me too… let’s add them back in…

Here’s a couple for String


/**
 *  String convenience method to trim leading and
 *  trailing whitespace.
 *  @returns string
 */
String.prototype.trim = function () {
    return this.replace(/^\s*/,'')
                     .replace(/\s*$/,'');
};

/**
 *  String convenience method for checking if the
 *  end of this string equals a given string.
 *
 *  @returns boolean
 *  @throws IllegalArgumentException for parameters
 *                          not of type String
 */
String.prototype.endsWith = function (s) {
    if ('string' != typeof s) {
        throw('IllegalArgumentException: Must pass a ' +
            ' string to String.prototype.endsWith()');
    }
    var start = this.length - s.length;
    return this.substring(start) == s;
};

Leave a Reply