用户工具

站点工具


jsutils

JS Utils 工具类

使用说明

/**
 * @sys    获取浏览器类型和版本信息
 */
var browser = (function(){
    var ua = window.navigator.userAgent.toLowerCase(), sys = null, s;
    if(s = ua.match(/rv:([\d.]+)\) like gecko/)){sys = {type:'ie',version:s[1]};}
    else if(s = ua.match(/msie ([\d.]+)/)){sys = {type:'ie',version:s[1]};}
    else if(s = ua.match(/firefox\/([\d.]+)/)){sys = {type:'firefox',version:s[1]};}
    else if(s = ua.match(/chrome\/([\d.]+)/)){sys = {type:'chrome',version:s[1]};}
    else if(s = ua.match(/opera.([\d.]+)/)){sys = {type:'opera',version:s[1]};}
    else if(s = ua.match(/version\/([\d.]+).*safari/)){sys = {type:'safari',version:s[1]};}
    else if(s = ua.match(/ucbrowser\/([\d.]+)/)){sys = {type:'uc',version:s[1]};}
    else if(s = ua.match(/micromessenger\/([\d.]+)/)){sys = {type:'wx',version:s[1]};}
    else{sys = {type:'unknown',version:'unknown'};}
    sys.isMobile = !!ua.match(/AppleWebKit.*Mobile.*!/) || !!ua.match(/(iPhone|iPod|Android|ios|iPad)/i);
    return sys;
})();

/**
 * @desc    格式化日期时间
 * @param   {[Date]}    date
 * @param   {[String]}    format时间日期格式
 * @return  {[String]}
 */
const formatTime = (date, format='yyyy-MM-dd hh:mm:ss') => {
    let dateObj = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
        "q+": Math.floor((date.getMonth() + 3) / 3),
        "S+": date.getMilliseconds()
    };

    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (let k in dateObj) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? dateObj[k] : ("00" + dateObj[k]).substr(("" + dateObj[k]).length));
        }
    }
    return format;
}

/**
 * @desc   判断是否为手机号
 * @param  {String|Number} str
 * @return {Boolean}
 */
const isPhoneNum = str => {
    return /^(0|86|17951)?(1[3-9][0-9])[0-9]{8}$/.test(str)
}

/**
 * @desc  判断是否为身份证号
 * @param  {String|Number} str
 * @return {Boolean}
 */
const isIdCard = str => {
    return /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(str)
}

/**
 * @desc   校验Ip地址格式
 * @param  {String} ipvale
 * @return {Boolean}
 */
const checkIp = ipvale => {
    // var regex = /^([1-9]|[1-9]\d|1\d{2}|2[0-1]\d|22[0-3])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}$/;
    var regex = /^(\d{1,2}|1\d\d|2[0-1]\d|22[0-3])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    return regex.test(ipvale);
}

/**
 * @desc   jsonString转化为object
 * @param  {String} str
 * @return {object|string|null}
 */
const JsonToString = str => {
    if (typeof(str) == "object") {
        return p;
    } else if (typeof(str) == "string") {
        try {
            return JSON.parse(str);
        } catch (e) {
            return str;
        }
    }
    return null;
}

/**
 * [数组分页]
 * @param     {[Number]}    pageNo   [页数]
 * @param     {[Number]}    pageSize [每页显示的数量]
 * @param     {[Array]}     array    [被分页的数组]
 * @return    {[Array]}
 */
const pagination = (pageNo, pageSize, array) => {
    var offset = (pageNo - 1) * pageSize;
    return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
}

/**
 * [修改URL参数]
 * @param     {[type]}    url [url]
 * @param     {[type]}    arg [key]
 * @param     {[type]}    val [value]
 * @return    {[type]}        [new url]
 */
const changeUrlArg = (url, arg, val) => {
    var pattern = arg + '=([^&]*)';
    var replaceText = arg + '=' + val;
    return url.match(pattern) ? url.replace(eval('/(' + arg + '=)([^&]*)/gi'), replaceText) : (url.match('[\?]') ? url + '&' + replaceText : url + '?' + replaceText);
}

/**
 * [获取URL参数]
 * @param     {[type]}    name [key]
 * @return    {[type]}         [value]
 */
const getUrlParameter = 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;
}

/**
 * [删除URL参数]
 * @param     {[type]}    url [url]
 * @param     {[type]}    ref [key]
 * @return    {[type]}        [new url]
 */
const delQueStr = (url, ref) => {
    var str = "";
    if (url.indexOf('?') != -1)
        str = url.substr(url.indexOf('?') + 1);
    else
        return url;
    var arr = "";
    var returnurl = "";
    var setparam = "";
    if (str.indexOf('&') != -1) {
        arr = str.split('&');
        for (i in arr) {
            if (arr[i].split('=')[0] != ref) {
                returnurl = returnurl + arr[i].split('=')[0] + "=" + arr[i].split('=')[1] + "&";
            }
        }
        return url.substr(0, url.indexOf('?')) + "?" + returnurl.substr(0, returnurl.length - 1);
    } else {
        arr = str.split('=');
        if (arr[0] == ref)
            return url.substr(0, url.indexOf('?'));
        else
            return url;
    }
}

/**
 * [Base64加密解密]
 * @encode     加密
 * @decode     解密
 */
const Base64 = {
  encode(str) {
      // first we use encodeURIComponent to get percent-encoded UTF-8,
      // then we convert the percent encodings into raw bytes which
      // can be fed into btoa.
      return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
          function toSolidBytes(match, p1) {
              return String.fromCharCode('0x' + p1);
          }));
  },
  decode(str) {
      // Going backwards: from bytestream, to percent-encoding, to original string.
      return decodeURIComponent(atob(str).split('').map(function (c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
      }).join(''));
  }
};

module.exports = {
    formatTime: formatTime,
    isPhoneNum: isPhoneNum,
    isIdCard: isIdCard,
    checkIp: checkIp,
    JsonToString: JsonToString,
    pagination: pagination,
    changeUrlArg: changeUrlArg,
    getUrlParameter: getUrlParameter,
    delQueStr: delQueStr,
    Base64: Base64
}
jsutils.txt · 最后更改: 2021/12/23 17:19 (外部编辑)