JS 用 prototype 扩展实现string过滤空格

JS的prototype是。。。。。。

实现对字符串 头和尾 空格的过滤,代码如下所示:

    //Trim the head and tail spaces
    String.prototype.Trim = function () {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    }

实现对字符串 头(左侧Left) 空格的过滤, 代码如下所示:

    //Trim the head spaces of current string
    String.prototype.LTrim = function () {
        return this.replace(/(^\s*)/g, "");
    }

实现对字符串 尾(右侧Right) 空格的过滤, 代码如下所示:

    //Trim the tail spaces of current string
    String.prototype.RTrim = function () {
        return this.replace(/(\s*$)/g, "");
    }

实现Contains方法(核心是用Index方法的返回值进行判断),代码如下所示:

    //Judge current string contains substring or not
    String.prototype.Contains = function (subStr) {
        var currentIndex = this.indexOf(subStr);
        if (currentIndex != -1) {
            return true;
        }
        else {
            return false;
        }
    }

 。。。。。

原文地址:https://www.cnblogs.com/mingmingruyuedlut/p/2871333.html