js工具类

常用js工具类

import Vue from 'vue';

/**
 * 内部通过utils.getInstance()获取当前实例对象
 */
class utils {
  static instance;

  static getInstance() {
    if (false === this.instance instanceof this) {
      this.instance = new this;
    }
    return this.instance;
  }

  constructor() {
    // console.log("构造器")
  }

  //字符串操作
  String = {
    // 清除字符串两边的空格
    trim(str = "") {
      return str.replace(/(^s*)|(s*$)/g, '');
    },
    //清除字符串所有的空格换行回车
    trimAll(str = "") {
      return str.replace(/[s
]+/g, "");
    },
    //替换一个匹配的字符串
    repStr(str = "", newStr = "") {
      return str.replace(new RegExp(str, "i"), newStr);
    },
    //替换所有匹配的字符串
    repStrAll(str = "", newStr = "") {
      return str.replace(new RegExp(str, "gi"), newStr);
    },

    //获取url中指定的参数值
    getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },

  }

  //数字操作
  Number = {}

  //数组操作
  Array = {}

  //对象操作
  Object = {
    /**
     * 获取指定对象的指定key
     * @param obj Object
     * @param keys String
     * @return subObj
     */
    subObj(obj, ...keys) {
      let sub_obj = {};
      keys.forEach(function (item) {
        if (obj[item] != undefined) {
          sub_obj[item] = obj[item];
        } else {
          sub_obj[item] = "";
        }
      });
      return sub_obj;
    },
    /**
     * 判断obj的对象是否有值
     * @param obj
     * @returns {boolean}
     */
    checkNull: function (obj) {
      var type = $k.getInstance().object.typeOf(obj);
      if (type == "number") {
        return true;
      } else if (type == "string" || type == "array") {
        return obj.length > 0;
      } else if (type == "json") {
        return JSON.stringify(obj).length > 2;
      }
    },
    /**
     * 判断对象是什么类型的
     */
    typeOf: function typeOf(obj) {
      var strObj = Object.prototype.toString.call(obj).toLowerCase();
      strObj = strObj.split(' ')[1].split(']')[0];
      if (strObj === 'object') {
        return 'json';
      } else {
        return strObj.toLowerCase();
      }
    },
    /**
     * 获取当前网站的协议,域名
     */
    domain: function () {
      /**域名,端口号为80时省略*/
      let host = window.location.host;
      /**http:或者https:*/
      let protocol = window.location.protocol;
      return window.location.origin;
    }
  }


  //日期操作
  Date = {
    /**
     * 时间格式化
     */
    format(date, format = 'yyyy-MM-dd hh:mm:ss') {
      return new Date(date).format(format);
    },

    /**
     * 获取当前时间戳
     */
    time(format = '') {
      return format == '' ? Date.parse(new Date()) / 1000 : Date.parse(new Date(format)) / 1000;
    },

    /**
     * 获取当前星期
     */
    week() {
      // 设置值班日期默认时间
      let myDate = new Date();
      let weekDays = new Array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
      // 获取当前天数 myDate.getDay();
      // 星期几
      return weekDays[myDate.getDay()];
    }
  }

  //常用的正则
  RegExp = {
    noChinese: new RegExp("^[x01-x7f]*$"),
    letterStart: /^[a-zA-Z][a-zA-Z0-9_]*$/,/*以字母开头的字母或数字*/
    chinese: /^[u4e00-u9fa5]$/, /*仅中文*/
    letter: /^[A-Za-z]+$/, /*仅字母*/
    CED: /^([A-Za-zd]|[u4E00-u9FA5])+$/, /*中文、字母、数字*/
    chiEng: /^([A-Za-z]|[u4E00-u9FA5])+$/, /*中文和字母*/
    numEng: /^[A-Za-z0-9]+$/, /*^[A-Za-z0-9]{4,40}$/;英文和数字*/
    posnum: /^[1-9]d*$/, /*正整数*/
    num: /^d{1}$/, /*只能有数字切不能为空*/
    pass: /([^su4E00-u9FA5]){6,20}$/, /*密码*/
    personName: /[u4E00-u9FA5]{2,10}(?:·[u4E00-u9FA5]{2,10})*/, /*人的姓名*/
    notnulls: /S/, /*不能为空*/
    filsenulls: /^S/, /*第一个字符不能为空格*/
    notspan: /^[^s]+$/, /*不能有空格*/
    notnull: /^S+$/, /*不能有空格并且不能为空*/
    notspe: new RegExp("[^\`~!@#$^&*()=|{}':;',\[\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]"), /*不能有特殊字符*/
    tel: /^[1][0-9]{10}$/, /*手机号*/
    wxchat: /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/,
    email: /w+((-w+)|(.w+))*@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+)*.[A-Za-z0-9]+/, /*邮箱*/
  }
}

/**原型链 */
!function () {

  // console.log();
  Date.prototype.format = function (format) {
    format = format || 'yyyy/MM/dd';
    /**
     * 日期格式化
     * eg:format="yyyy-MM-dd hh:mm:ss";
     */
    var o = {
      "M+": this.getMonth() + 1, // month
      "d+": this.getDate(), // day
      "h+": this.getHours(), // hour
      "m+": this.getMinutes(), // minute
      "s+": this.getSeconds(), // second
      "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
      "S": this.getMilliseconds()
      // millisecond
    };
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
        - RegExp.$1.length));
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1
          ? o[k]
          : ("00" + o[k]).substr(("" + o[k]).length));
      }
    }
    return format;
  };

}();

Vue.prototype.$utils = utils.getInstance();
原文地址:https://www.cnblogs.com/zhizou/p/11646079.html