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

Array

Date

Note : Please post one extended method per answer.

Comments 21

  • 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
    
  • There are a ton of String.prototype functions from James Padolsey

    https://github.com/padolsey/string.prototype

    These include:

    • camelize
    • contains
    • count
    • enclose
    • extract
    • forEach
    • forEachWord
    • linkify
    • many
    • randomize
    • remove
    • reverse
    • shorten
    • sort
    • toDOM
    • trim
    • wrap
  • // 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

  • Function.prototype.bind from the Prototype library.

    Similar to call and apply but allows you to return a reference to a function that is called in a particular context instead of executing it immediately. Also allows you to curry parameters. It’s so useful that it became a part of ECMAScript 5 and is already being implemented natively in browsers.

    Function.prototype.bind = function() {
      var __method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
      return function() {
        var local_args = args.concat(Array.prototype.slice.call(arguments));
        if (this !== window) local_args.push(this);
        return __method.apply(object, local_args);
      }
    }
    
  • 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) 
    }
    
  • 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

  • I have used the Array.Map function outlined by Scott Koon a couple of times.

    http://www.lazycoder.com/weblog/2009/08/12/a-simple-map-function-for-plain-javascript-arrays/

    Array.prototype.map = function(fn) {
        var r = [];
        var l = this.length;
        for(i=0;i<l;i++)
        {
            r.push(fn(this[i]));
        }
        return r; 
    };
    
  • 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 🙂

  • These two are wrappers for inserting and deleting elements from a particular position in an Array because I don’t like the name splice.

    // insert element at index
    Array.prototype.insertAt = function(element, index) {
        this.splice(index, 0, element);
    }
    
    // delete element from index
    Array.prototype.removeAt = function(index) {
        this.splice(index, 1);
    }
    

    Some more useful Array methods to get away from using indexes:

    Array.prototype.first = function() {
        return this[0] || undefined;
    };
    
    Array.prototype.last = function() {
        if(this.length > 0) {
            return this[this.length - 1];
        }
        return undefined;
    };
    
    Array.prototype.max = function(array){
        return Math.max.apply(Math, array);
    };
    
    Array.prototype.min = function(array){
        return Math.min.apply(Math, array);
    };
    

    Some useful functions from the MooTools library:

    Function.delay

    Used to execute a function after the given milliseconds have elapsed.

    // alerts "hello" after 2 seconds.
    (function() {
        alert("hello");
    }).delay(2000);    ​
    

    Number.times

    Similar to Ruby’s times method for numbers, this accepts a function and executes it N times where N is the numbers value.

    // logs hello 5 times
    (5).times(function() {
        console.log("hello");
    });
    
  • 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;
    };
    
  • There is a nice article at http://maiaco.com/articles/js/missingArrayFunctions.php describing six helpful functions to add to the Array prototype. The functions are linearSearch (same as indexOf given in another answer), binarySearch, retainAll, removeAll, unique, and addAll. The article also includes the JavaScript code for each of the six functions and example code showing how to use them.

  • This is a prototype function for capitalizing a string:

    String.prototype.capitalize = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }
    
  • Use something like the underscore.js library or for Angular use lodash library.

发表评论

电子邮件地址不会被公开。 必填项已用*标注