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

Viewed 65936

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

String

Array

Date

Note : Please post one extended method per answer.

21 Answers

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

String.format

String.prototype.format = function (values) {

    var regex = /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g;

    var getValue = function (key) {
            if (values == null || typeof values === 'undefined') return null;

            var value = values[key];
            var type = typeof value;

            return type === 'string' || type === 'number' ? value : null;
        };

    return this.replace(regex, function (match) {
        //match will look like {sample-match}
        //key will be 'sample-match';
        var key = match.substr(1, match.length - 2);

        var value = getValue(key);

        return value != null ? value : match;
    });
};

Usage:

alert('Program: {key1} {key2}'.format({ 'key1' : 'Hello', 'key2' : 'World' })); //alerts Program: hello world
// left trim
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, '');
}

// right trim
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, '');
}

// left and right trim
String.prototype.trim = function () {
    return this.ltrim().rtrim();
}

String Padding :

String.prototype.padLeft = function (length, character) { 
     return new Array(length - this.length + 1).join(character || ' ') + this; 
}
'trial'.padLeft(7, 'X'); // output : 'XXtrial'
'trial'.padLeft(7);      // output : '  trial'



String.prototype.padRight = function (length, character) { 
     return this + new Array(length - this.length + 1).join(character || ' '); 
}
'trial'.padRight(7, 'X'); // output : 'trialXX'
'trial'.padRight(7);      // output : 'trial  '

PHP.JS is a very nice effort to port most of PHP's functions to JavaScript. They currently have an extremely impressive list:

Online at: http://phpjs.org/functions/index

The various list manipulation prototypes are always great. Since you want only one per post, I'll just post foldl, which I discovered via SML (it "folds" the list, left to right, it has a counter part in foldr of course).

Array.prototype.foldl = function(fnc,start) {
    var a = start;
    for (var i = 0; i < this.length; i++) {
        a = fnc(this[i],a);
    }
    return a;
}

Some trivial examples could be:

var l = ["hello" , "world"];
l.foldl(function(i, acc) { return acc+" "+i; }, "") // => returns "hello world"

Sadly, the failure of standard DOM methods to return true arrays makes alot of these such methods rather useless. And if you're using a Lib of some sort, they often define methods like these already (map, filter, exists, etc).

Date.toMidnight

Date.prototype.toMidnight = function(){ 
  this.setMinutes(0); 
  this.setSeconds(0); 
  this.setHours(0) 
}

Array contains:

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

Usage:

var arr = [1, 2, 3];
alert(arr.contains(2));

This little helper function tells you if your array contains an object. If it does then the index of the object is returned, otherwise -1 is returned.

Free Friday afternoon tip: don't ever ever ever modify the Object prototype. That would be just asking for a whole world of pain - I learnt this the hard way :)

Here's the nice extension for the Date object that allows you to format the date very easily. It uses PHP's date syntax so those familiar with PHP will get it in no time. Others have a huge list of possible switches on the site as well. Personally I haven't found easier way to format dates to various formats.

Date Format

Use the prototype chain like this:

String.prototype.AddWorld = function() { return this+'World' }

"Hello ".AddWorld(); // returns the string "Hello World"
// This replaces all instances of 'from' to 'to' even when
// 'from' and 'to' are similar (i.e .replaceAll('a', 'a '))
String.prototype.replaceAll = function(from, to) {
    var k = this;
    var i = 0;
    var j = from.length;
    var l = to.length;

    while (i <= k.length)
        if (k.substring(i, i + j) == from) {
        k = k.substring(0, i) + k.substring(i).replace(from, to);
        i += l;
    }
    else
        i++;

    return k;
};
Related