zoukankan      html  css  js  c++  java
  • js字符串的常用处理

    //把字符串中所有的s1替换为s2

    String.prototype.replaceAll = function (s1, s2) {
        return this.replace(new RegExp(s1, "gm"), s2);
    }

    //校验字符串是否为空
    String.prototype.isEmpty = function () {
        return /^s*$/.test(this);
    }

    //去除字符串左右两边的空格
    String.prototype.trim = function () {
        return this.replace(/(^s*)|(s*$)/g, "");
    }

    //去除字符串左边的空格
    String.prototype.ltrim = function () {
        return this.replace(/(^s*)/g, "");
    }

    //去除字符串右边的空格
    String.prototype.rtrim = function () {
        return this.replace(/(s*$)/g, "");
    }

    //校验字符串是否以str为开头
    if (typeof(String.prototype.startWith) != "function") {
        String.prototype.startWith = function (str) {
            var reg = new RegExp("^" + str);
            return reg.test(this);
        }
    }

    //校验字符串是否以str为结尾
    if (typeof(String.prototype.endWith) != "function") {
        String.prototype.endWith = function (str) {
            var reg = new RegExp(str + "$");
            return reg.test(this);
        }
    }

    //根据传入的字符串分组 比如str= ",,;; " 是根据字符串中 ,,;; 将字符串分割成数组
    String.prototype.splitByStr = function (str) {
        var key = this;
        var reg = new RegExp("[" + str + "]");
        var arr = [];
        var tmp = reg.exec(key);
        while (tmp) {
            var tmpStr = key.substring(0, key.indexOf(tmp[0]));
            if (tmpStr.length > 0) {
                arr.push(tmpStr);
            }
            key = key.substring(tmpStr.length + 1);
            tmp = reg.exec(key);
        }
        arr.push(key);
        return arr;
    }

  • 相关阅读:
    PHP常用字符串函数
    PHP 中解析 url 并得到 url 参数
    PHP中的10个实用函数
    虚拟主机知识全解
    php三种常用的加密解密算法
    Javascript中的位运算符和技巧
    ECMAScript 5中新增的数组方法
    捕捉小括号获取的内容保存在RegExp的$1 $2..属性中
    js获取浏览器窗口的大小
    关于switch的思考和总结
  • 原文地址:https://www.cnblogs.com/zdlblogs/p/6297479.html
Copyright © 2011-2022 走看看