阅读 100

常用代码片段

判断移动还是PC,以及浏览器内核

    var browser = {
        versions: function() {
            var u = navigator.userAgent;
            return {
                trident: u.indexOf('Trident') > -1,
                presto: u.indexOf('Presto') > -1,
                isChrome: u.indexOf("chrome") > -1,
                isSafari: !u.indexOf("chrome") > -1 && (/webkit|khtml/).test(u),
                isSafari3: !u.indexOf("chrome") > -1 && (/webkit|khtml/).test(u) && u.indexOf('webkit/5') != -1,
                webKit: u.indexOf('AppleWebKit') > -1,
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
                qq: u.toLowerCase().indexOf("15b202 qq") > -1, //QQ APP 内置浏览器
                weixin: u.toLowerCase().indexOf("micromessenger") > -1, //微信app内置浏览器
                mobile: !!u.match(/AppleWebKit.*Mobile.*/),
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
                iPhone: u.indexOf('iPhone') > -1,
                iPad: u.indexOf('iPad') > -1,
                iWinPhone: u.indexOf('Windows Phone') > -1
            };
        }()
    }
复制代码

身份证验证

   //第二代身份证号码正则
    let isTrue = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    //第一代身份证正则表达式(15位)
    let isTrue = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
    //函数验证2代身份证;
     function identityCodeValid(code) {
        var city = {
            11: "北京",
            12: "天津",
            13: "河北",
            14: "山西",
            15: "内蒙古",
            21: "辽宁",
            22: "吉林",
            23: "黑龙江 ",
            31: "上海",
            32: "江苏",
            33: "浙江",
            34: "安徽",
            35: "福建",
            36: "江西",
            37: "山东",
            41: "河南",
            42: "湖北 ",
            43: "湖南",
            44: "广东",
            45: "广西",
            46: "海南",
            50: "重庆",
            51: "四川",
            52: "贵州",
            53: "云南",
            54: "西藏 ",
            61: "陕西",
            62: "甘肃",
            63: "青海",
            64: "宁夏",
            65: "新疆",
            71: "台湾",
            81: "香港",
            82: "澳门",
            91: "国外 "
        };
        var tip = "";
        var pass = true;
        if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
            tip = "身份证号格式错误";
            pass = false;
        } else if (!city[code.substr(0, 2)]) {
            tip = "地址编码错误";
            pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if (parity[sum % 11] != code[17]) {
                    tip = " 校验位错误";
                    pass = false;
                }
            }
        }
        return pass;
    }
复制代码

日期格式化

//**获取当前日期格式化后的字符串**获取当前日期格式化后的字符串;只有两种yyyy-MM-dd和yyyy-MM-dd HH:mm;
//getFormatedDate()默认为yyyy-MM-dd;
//getFormatedDate("HH:mm")为yyyy-MM-dd HH:mm;
  function getFormatedDate(type = "yyyy-MM-dd") {
        let date = new Date();
        let [year, month, day, hours, minutes] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()];
        if (~type.indexOf("HH:mm")) {
            return `${year}-${month>9?month:("0"+month)}-${day>9?day:("0"+day)} ${hours>9?hours:("0"+hours)}:${minutes>9?minutes:("0"+minutes)}`
        } else {
            return `${year}-${month>9?month:("0"+month)}-${day>9?day:("0"+day)}`
        }
    }
    
//**获取相对当前偏移以后的日期**n为偏移的天数,正数为向后偏移,负数为向后偏移    
 function getDateOffset(n) {
        let date = new Date();
        date.setDate(date.getDate() + n);
        let [year, month, day, hours, minutes] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()];
        let s = `${year}-${month>9?month:("0"+month)}-${day>9?day:("0"+day)} ${hours>9?hours:("0"+hours)}:${minutes>9?minutes:("0"+minutes)}`;
        return s
    }
复制代码

手机号码正则

let isPhoneNum = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/;

邮箱正则

let isEmail =/^([A-Za-z0-9_-.\u4e00-\u9fa5])+@([A-Za-z0-9_-.])+.([A-Za-z]{2,8})$/;

用户名正则

//用户名正则,4到16位(字母,数字,下划线,减号)
; let isTrue = /[1]{4,16}$/;

密码正则:

密码正则,以字母开头,长度在6~18之间,只能包含字母、数字和下划线;
let isTrue =[2]\w{5,17}$;

强密码正则,最少6位,包括至少1个大写字母,1个小写字母,1个数字,1个特殊字符
let isTrue = /^.(?=.{6,})(?=.\d)(?=.[A-Z])(?=.[a-z])(?=.*[!@#%^&*? ]).*/;

类型判断;

const isType = function(type, arg) { return Object.prototype.toString.call(arg) === [object ${type}] }

##保留小数点n位(不进行4舍5入)

function k(v) { return Math.floor(v * 10) % 10 === 0 ? v + ".0" : Math.floor(v * 10) / 10 } ##保留小数点n位(进行4舍5入) function k(v) { return v.toFixed(1) }

多条件排序

var sort = function(arr = [], sortBy = []) {
    let len = sortBy.length;
    arr.sort(function(a, b) {
        let i = 0;
        while (i < len) {
            if (a[sortBy[i]].toString().localeCompare(b[sortBy[i]].toString())) {
                break;
            } else {
                i++
            }
        }
        return a[sortBy[i]].toString().localeCompare(b[sortBy[i]].toString())
    })
    console.log(arr)
    return arr
}
var a = [{
    name: "zhoulin",
    age: 20,
    zhName: "周林"
}, {
    name: "renboen",
    age: 18,
    zhName: "任博恩"
}, {
    name: "zhaochen",
    age: 15,
    zhName: "赵晨"
}, {
    name: "zhoulinlin",
    age: 28,
    zhName: "周林"
}, {
    name: "zao",
    age: 28,
    zhName: "周林"
}];
sort(a, ["zhName", "age", "name"])
复制代码

  1. a-zA-Z0-9_- ↩︎

  2. a-zA-Z ↩︎

文章分类
前端