What are useful JavaScript methods that extends built-in objects? [closed]

What are your most useful, most practical methods that extends built-in JavaScript objects like String, Array, Date, Boolean, Math, etc.?

String

  • format
  • trim
  • padding
  • replaceAll & replaceAll

Array

  • indexOf

Date

  • toMidnight

Note : Please post one extended method per answer.


String Replace All :

String.prototype.replaceAll = function(search, replace)
{
    //if replace is not sent, return original string otherwise it will
    //replace search string with 'undefined'.
    if (replace === undefined) {
        return this.toString();
    }

    return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};

var str = 'ABCADRAE';
alert(str.replaceAll('A','X')); // output : XBCXDRXE

Here's another implementation of String.replaceAll() method

String.prototype.replaceAll = function(search, replace) {
    if (replace === undefined) {
        return this.toString();
    }
    return this.split(search).join(replace);
}

The difference between this one and solution posted here is that this implementation handles correctly regexp special characters in strings as well as allows for word matching


Array.prototype.indexOf = Array.prototype.indexOf || function (item) {
    for (var i=0; i < this.length; i++) {
        if(this[i] === item) return i;
    }
    return -1;
};

Usage:

var list = ["my", "array", "contents"];
alert(list.indexOf("contents"));     // outputs 2