给JS对象添加扩展方法

    如何在JS中像C#语法一样,调用str.Trim()呢?

    在JS中string对象自己也有trim方法,可通过str.trim()实现

    在jQuery中jquery对象也封装了trim方法,可通过$.trim(str)实现

    可是对于TrimStart,TrimEnd的方法,JS的string对象并没有对应方法,jquery也同样没有封装。所以对于使用非常多的方法,我们可以自己封装。这里拿Trim的一组方法为例,如下

1.给jQuery对象添加扩展

            jQuery.extend({
                trim: function (text) {//jQuery已自带
                    return text.replace(/(^\s*)|(\s*$)/g, "");
                },
                trimLeft: function () {
                    return this.replace(/(^\s*)/g, '');
                },
                trimRight : function () {
                    return this.replace(/(\s*$)/g, '');
                }
            })

2.给JS的String对象添加扩展

        //String.prototype.trim = function () {//js1.8版本以上自带,这里强烈建议不重复构写方法,原因会超多次走这个方法
        //    return this.replace(/(^\s*)|(\s*$)/g, '');
        //}

        String.prototype.trimLeft = function () {
            return this.replace(/(^\s*)/g, '');
        }

        String.prototype.trimRight = function () {
            return this.replace(/(\s*$)/g, '');
        }

如何调用

            var str = '       空格    ';
            var res1 = str.trim();
            var res2 = $.trim(str);
            var res3 = str.trimLeft();
            var res4 = $.trimRight(str);


猜你喜欢

转载自blog.csdn.net/spw55381155/article/details/80193834