js常见方法

1.姓名脱敏:2个字:董*,2字以上:董*谭

export const cust = (name) => { //姓名脱敏
	if (name && name != undefined && name != '') {
		let name2 = '';
		if (name.length == 2) {
			name = name.substring(0, 1) + '*'
		}
		if (name.length > 2) {
			name = name.substring(0, 1) + '*' + name.charAt(name.length - 1)
		}
		return name
	} else {
		return name
	}
}

2.验证手机号码

export const isMobile = (s) => {
    return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(s)
}

3.验证电话号码

export const isPhone = (s) => {
    return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(s)
}

4.验证邮箱

export const isEmail = (s) => {
    return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
    ///^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/
}

5.是否url地址

export const isURL = (s) => {
    return /^http[s]?:\/\/.*/.test(s)
}

6.是否数字

export const isNumber = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Number'
}

7.是否为null

export const isNull = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Null'
}

8.是否undefined

export const isUndefined = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined'
}

9.是否对象

export const isObj = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Object'
}

10.是否数组

export const isArray = (o) => {
    return Object.prototype.toString.call(o).slice(8, -1) === 'Array'
}

11.获取url参数

export const getQueryString = (name) => {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    const search = window.location.search.split('?')[1] || '';
    const r = search.match(reg) || [];
    return r[2];
}

12.字符转换,type: 1:首字母大写 2:首字母小写 3:大小写转换 4:全部大写 5:全部小写

export const changeCase = (str, type) => {
    type = type || 4
    switch (type) {
        case 1:
            return str.replace(/\b\w+\b/g, function (word) {
                return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();

            });
        case 2:
            return str.replace(/\b\w+\b/g, function (word) {
                return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
            });
        case 3:
            return str.split('').map(function (word) {
                if (/[a-z]/.test(word)) {
                    return word.toUpperCase();
                } else {
                    return word.toLowerCase()
                }
            }).join('')
        case 4:
            return str.toUpperCase();
        case 5:
            return str.toLowerCase();
        default:
            return str;
    }
}

13.去除空格,type: 1-所有空格 2-前后空格 3-前空格 4-后空格

export const trim = (str, type) => {
    type = type || 1
    switch (type) {
        case 1:
            return str.replace(/\s+/g, "");
        case 2:
            return str.replace(/(^\s*)|(\s*$)/g, "");
        case 3:
            return str.replace(/(^\s*)/g, "");
        case 4:
            return str.replace(/(\s*$)/g, "");
        default:
            return str;
    }
}

14.最大值

export const max = (arr) => {
    return Math.max.apply(null, arr);
}

15.最小值

export const min = (arr) => {
    return Math.min.apply(null, arr);
}

16.数组去重

export const unique = (arr) => {
    if (Array.hasOwnProperty('from')) {
        return Array.from(new Set(arr));
    } else {
        var n = {}, r = [];
        for (var i = 0; i < arr.length; i++) {
            if (!n[arr[i]]) {
                n[arr[i]] = true;
                r.push(arr[i]);
            }
        }
        return r;
    }
}

17.验证格式

export const checkStr = (str, type) => {
    switch (type) {
        case 'phone':   //手机号码
            return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
        case 'tel':     //座机
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case 'card':    //身份证
            return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
        case 'pwd':     //密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线
            return /^[a-zA-Z]\w{5,17}$/.test(str)
        case 'postal':  //邮政编码
            return /[1-9]\d{5}(?!\d)/.test(str);
        case 'QQ':      //QQ号
            return /^[1-9][0-9]{4,9}$/.test(str);
        case 'email':   //邮箱
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
        case 'money':   //金额(小数点2位)
            return /^\d*(?:\.\d{0,2})?$/.test(str);
        case 'URL':     //网址
            return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
        case 'IP':      //IP
            return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
        case 'date':    //日期时间
            return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
        case 'number':  //数字
            return /^[0-9]$/.test(str);
        case 'english': //英文
            return /^[a-zA-Z]+$/.test(str);
        case 'chinese': //中文
            return /^[\\u4E00-\\u9FA5]+$/.test(str);
        case 'lower':   //小写
            return /^[a-z]+$/.test(str);
        case 'upper':   //大写
            return /^[A-Z]+$/.test(str);
        case 'HTML':    //HTML标记
            return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
        default:
            return true;
    }
}

18.是否是微信浏览器

export const isWeiXin = () => {
    return ua.match(/microMessenger/i) == 'micromessenger'
}

19.是否是移动端

export const isDeviceMobile = () => {
    return /android|webos|iphone|ipod|balckberry/i.test(ua)
}

20.手机机型: 是否ios

export const isIos = () => {
    var u = navigator.userAgent;
    if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {  //安卓手机
        return false
    } else if (u.indexOf('iPhone') > -1) {//苹果手机
        return true
    } else if (u.indexOf('iPad') > -1) {//iPad
        return false
    } else if (u.indexOf('Windows Phone') > -1) {//winphone手机
        return false
    } else {
        return false
    }
}

21.是否为PC端

export const isPC = () => {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
        "SymbianOS", "Windows Phone",
        "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

22.手机号脱敏

export const phone = (phone) => { //手机号脱敏
	if (phone && phone != '') {
		phone = phone.substring(0, 3) + "****" + phone.substring(7, 11)
		return phone
	} else {
		return phone
	}
}

23.身份证中间11位脱敏

export const idCard = (idCardNum) => { //身份证中间11位脱敏
	if (idCardNum && idCardNum != undefined && idCardNum != '') {
		let idCardNum1 = idCardNum.substring(4, 15);
		idCardNum = idCardNum.replace(idCardNum1, '***********')
		return idCardNum
	} else {
		return idCardNum
	}
}

24.时间格式转换

// *
//  * 日期对象转为日期字符串
//  * @param date 需要格式化的日期对象
//  * @param sFormat 输出格式,默认为yyyy-MM-dd                         年:y,月:M,日:d,时:h,分:m,秒:s
//  * @example  dateFormat(new Date())                               "2017-02-28"
//  * @example  dateFormat(new Date(),'yyyy-MM-dd')                  "2017-02-28"
//  * @example  dateFormat(new Date(),'yyyy-MM-dd hh:mm:ss')         "2017-02-28 09:24:00"
//  * @example  dateFormat(new Date(),'hh:mm')                       "09:24"
//  * @example  dateFormat(new Date(),'yyyy-MM-ddThh:mm:ss+08:00')   "2017-02-28T09:24:00+08:00"
//  * @returns {string}

export const dateFormat = (value, dateFormat) => {
	let date = new Date(Number(value));
	if (date.toString() === 'Invalid Date') {
		date = new Date(value.replace(/\-/g, "/"));
	}
	let time = {
		Year: 0,
		TYear: '0',
		Month: 0,
		TMonth: '0',
		Day: 0,
		TDay: '0',
		Hour: 0,
		THour: '0',
		hour: 0,
		Thour: '0',
		Minute: 0,
		TMinute: '0',
		Second: 0,
		TSecond: '0',
		Millisecond: 0
	};
	time.Year = date.getFullYear();
	time.TYear = String(time.Year).substr(2);
	time.Month = date.getMonth() + 1;
	time.TMonth = time.Month < 10 ? "0" + time.Month : String(time.Month);
	time.Day = date.getDate();
	time.TDay = time.Day < 10 ? "0" + time.Day : String(time.Day);
	time.Hour = date.getHours();
	console.log(time.Hour)
	time.THour = time.Hour < 10 ? "0" + time.Hour : String(time.Hour);
	time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12;
	time.Thour = time.hour < 10 ? "0" + time.hour : String(time.hour);
	time.Minute = date.getMinutes();
	time.TMinute = time.Minute < 10 ? "0" + time.Minute : String(time.Minute);
	time.Second = date.getSeconds();
	time.TSecond = time.Second < 10 ? "0" + time.Second : String(time.Second);
	time.Millisecond = date.getMilliseconds();

	return dateFormat.replace(/yyyy/ig, String(time.Year))
		.replace(/yyy/ig, String(time.Year))
		.replace(/yy/ig, time.TYear)
		.replace(/y/ig, time.TYear)
		.replace(/MM/g, time.TMonth)
		.replace(/M/g, String(time.Month))
		.replace(/dd/ig, time.TDay)
		.replace(/d/ig, String(time.Day))
		.replace(/HH/g, time.THour)
		.replace(/H/g, String(time.Hour))
		.replace(/hh/g, time.Thour)
		.replace(/h/g, String(time.hour))
		.replace(/mm/g, time.TMinute)
		.replace(/m/g, String(time.Minute))
		.replace(/ss/ig, time.TSecond)
		.replace(/s/ig, String(time.Second))
		.replace(/fff/ig, String(time.Millisecond))
}

25.获取21天后的时间

export const Tian21 = (time) => {
	var time21 = new Date(time);
	var endTime = time21.setDate(time21.getDate() + 21)
	return endTime
}

26.获取20分钟后时间

export const mintius20 = (time) => {
	var date = new Date(time);
	//1. js获取当前时间
	var min = date.getMinutes();
	//2. 获取当前分钟
	date.setMinutes(min + 20);
	//3. 设置当前时间+20分钟:把当前分钟数+20后的值重新设置为date对象的分钟数
	let time1 = Date.parse(date)
	return time1
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值