有哪些有用的JavaScript方法可以扩展内置对象?

Can*_*var 41 javascript

扩展内置JavaScript对象(如String,Array,Date,Boolean,Math等)的最有用,最实用的方法是什么?

排列

日期

注意:请为每个答案发布一个扩展方法.

Can*_*var 40

字符串全部替换:

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
Run Code Online (Sandbox Code Playgroud)

  • 另一个改进:如果你添加任何正则表达式特殊字符,你可能会得到意想不到的结果.即如果你通过'.' 作为搜索字符串,您将替换所有字符.为了避免这种改变你的正则表达式像新的RegExp('['+ search']') (3认同)
  • @RaYell - 如果你想一次替换多个角色,那将无法工作,例如`'foobar'.replaceAll('foo')`.我认为最好明确将正则表达式作为第一个参数接受. (2认同)

RaY*_*ell 38

这是String.replaceAll()方法的另一种实现方式

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

这个和这里发布的解决方案之间的区别在于此实现正确处理字符串中的regexp特殊字符以及允许字匹配


Mak*_*leh 16

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

用法:

var list = ["my", "array", "contents"];
alert(list.indexOf("contents"));     // outputs 2
Run Code Online (Sandbox Code Playgroud)

  • 此方法在大多数浏览器中实现,因此您可以在覆盖已经完成的操作之前添加存在性检查.IMO你应该把这个代码包装在内(如果(Array.prototype.indexOf === undefined){...} (4认同)

Jon*_*son 8

James Padolsey有很多String.prototype函数

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

这些包括:

  • camelize
  • 包含
  • 计数
  • 提取
  • 的forEach
  • forEachWord
  • linkify
  • 许多
  • 随机
  • 去掉
  • 相反
  • 缩短
  • 分类
  • toDOM
  • 修剪
  • 包裹


Sol*_*ogi 8

的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;
    });
};
Run Code Online (Sandbox Code Playgroud)

用法:

alert('Program: {key1} {key2}'.format({ 'key1' : 'Hello', 'key2' : 'World' })); //alerts Program: hello world
Run Code Online (Sandbox Code Playgroud)


RaY*_*ell 7

// 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();
}
Run Code Online (Sandbox Code Playgroud)


Can*_*var 5

字符串填充:

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  '
Run Code Online (Sandbox Code Playgroud)


Fra*_*ger 0

像这样使用原型链:

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

"Hello ".AddWorld(); // returns the string "Hello World"
Run Code Online (Sandbox Code Playgroud)

  • -1,因为它没有用或不实用。 (9认同)