utils.js 5.78 KB
/**
 * 获取当前链接参数
 * @param {*} name
 */
export const getLinkParam = name => {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null;
};

/**
 * 去掉字符串两端空格 trim
 * @param {string} str
 */
export const trim = str => {
  return str.replace(/(^\s*)|(\s*$)/g, '');
}

/**
 * 验证邮箱
 * @param {string} str
 */
export const checkEmail = str => {
  let re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
  if (re.test(str)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 验证手机 1开头+10位数
 * @param {string} str
 */
export const checkMobile = str => {
  let re = /^1\d{10}$/;
  // let re = /^(13[0-9]|14[57]|15[0-9]|17[0-9]|18[0-9])\d{8}$/; //严格模式
  if (re.test(str)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 获取Uuid
 */
export const uuid = () => {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid;
}


/**
 * 设置cookies
 * @param {*} name
 * @param {*} value
 * @param {*} Days
 */
export const setCookie = (name, value, Days = 0) => {
  if (Days <= 0) Days = 30;
  var exp = new Date();
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  document.cookie = name + "=" + encodeURI(value) + ";expires=" + exp.toUTCString();
}


/**
 * 获取cookies
 * @param {*} name
 * @param {*} value
 * @param {*} Days
 */
export const getCookie = (name) => {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if (arr = document.cookie.match(reg)) {
    return decodeURI(arr[2]);
  } else {
    return "";
  }
}

/**
 * 删除cookies
 * @param {*} name
 */
export const deleteCookie = (name) => {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval != null)
    document.cookie = name + "=" + cval + ";expires=" + exp.toUTCString();
}

/**
 * 判断是否微信客户端
 * @param {*} name
 */
export const isWeiXin = () => {
  var ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
}


/**
 * 时间戳格式化(yyyy-MM-dd hh:mm:ss)
 * @param {*} timestamp
 * @param {*} format
 */
export const timestampFormat = (timestamp, format) => {
  Date.prototype.Format = function (fmt) {
    var o = {
      "M+": this.getMonth() + 1, //月份
      "d+": this.getDate(), //日
      "h+": this.getHours(), //小时
      "m+": this.getMinutes(), //分
      "s+": this.getSeconds(), //秒
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
      "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
    return fmt;
  }

  if (timestamp && timestamp.length == 10) timestamp += "000";

  var date = new Date();
  if (timestamp) date.setTime(timestamp);
  if (format == null || format == "") {
    format = "yyyy-MM-dd hh:mm:ss";
  }
  return date.Format(format);
};

/**
 * 日期转时间戳
 * @param {*} stringTime
 */
export const dateParse = stringTime => {
  if (stringTime) {
    var date = new Date(stringTime);
  } else {
    var date = new Date();
  }
  return Date.parse(date);
};


/**
 * 生成指定范围内的随机数
 * @param {*} min
 * @param {*} max
 */
export const getRandom = (min, max) => {
  var c = max - min + 1;
  return Math.floor(Math.random() * c + min);
};


/**
 * 日期格式化
 */
export const formatDate = {
  SIGN_REGEXP: /([yMdhsm])(\1*)/g,
  DEFAULT_PATTERN: 'yyyy-MM-dd',
  padding: function (s, len) {
    var len = len - (s + '').length;
    for (var i = 0; i < len; i++) {
      s = '0' + s;
    }
    return s;
  },
  format: function (date, pattern) {
    pattern = pattern || formatDate.DEFAULT_PATTERN;
    return pattern.replace(formatDate.SIGN_REGEXP, function ($0) {
      switch ($0.charAt(0)) {
        case 'y':
          return formatDate.padding(date.getFullYear(), $0.length);
        case 'M':
          return formatDate.padding(date.getMonth() + 1, $0.length);
        case 'd':
          return formatDate.padding(date.getDate(), $0.length);
        case 'w':
          return date.getDay() + 1;
        case 'h':
          return formatDate.padding(date.getHours(), $0.length);
        case 'm':
          return formatDate.padding(date.getMinutes(), $0.length);
        case 's':
          return formatDate.padding(date.getSeconds(), $0.length);
      }
    });
  },
  parse: function (dateString, pattern) {
    var matchs1 = pattern.match(formatDate.SIGN_REGEXP);
    var matchs2 = dateString.match(/(\d)+/g);
    if (matchs1.length == matchs2.length) {
      var _date = new Date(1970, 0, 1);
      for (var i = 0; i < matchs1.length; i++) {
        var _int = parseInt(matchs2[i]);
        var sign = matchs1[i];
        switch (sign.charAt(0)) {
          case 'y':
            _date.setFullYear(_int);
            break;
          case 'M':
            _date.setMonth(_int - 1);
            break;
          case 'd':
            _date.setDate(_int);
            break;
          case 'h':
            _date.setHours(_int);
            break;
          case 'm':
            _date.setMinutes(_int);
            break;
          case 's':
            _date.setSeconds(_int);
            break;
        }
      }
      return _date;
    }
    return null;
  }

}