What are useful JavaScript methods that extends built

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.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;
    };
    

    用法:

    var list = ["my", "array", "contents"];
    alert(list.indexOf("contents"));     // outputs 2
    
    链接地址: http://www.djcxy.com/p/2744.html

    上一篇: 相当于PHP的preg的JavaScript

    下一篇: 什么是扩展构建的有用的JavaScript方法