前端 js 常用的辅助方法

引言

做项目时,每个人会多或少都需要一些自己封装一个辅助方法来帮助自己的项目稳定进行,也可以方便自己在改动一个方法时全局一起变动,故而会封装。

号码中间数字转化

export const replaceStart = (str, frontLen, endLen) => {
    
    
	// str:字符串,frontLen:前面保留位数,endLen:后面保留位数。
	var len = str.length - frontLen - endLen;
	var start = '';
	for (var i = 0; i < len; i++) {
    
    
		start += '*';
	}
	return str.substring(0, frontLen) + start + str.substring(str.length - endLen);
}

大额数字转化

export const numFormat = (num) => {
    
    
	if (num >= 10000) {
    
    
		num = Math.round(num / 1000) / 10 + 'w+';
	}
	return num;
};

验证拼接图片路径

export const isHttpOrHttps = (url) => {
    
    
	const reg = /http[s]{0,1}:\/\/([\w.]+\/?)\S*/;
	if (url) {
    
    
		if (reg.test(url)) {
    
    
			return url
		} else {
    
    
			return process.uniEnv.UNI_BASE_OSS_IMAGES + url
		}
	} else {
    
    
		return;
	}
};
// process.uniEnv.UNI_BASE_OSS_IMAGES 字段根据项目改变

随机生成文件名

export const randomString = (len, suffix) => {
    
    
	const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz12345678';
	const maxPos = chars.length;
	let fileName = '';
	for (let i = 0; i < len; i++) {
    
    
		fileName += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return fileName + '_' + new Date().getTime() + '.' + suffix;
};

根据时间戳的差值计算时间(包含天)

export const getTimeContainDay = (aftertimestamp) => {
    
    
	const nowtimestamp = new Date().getTime()
	const difValue = aftertimestamp - nowtimestamp;
	// 计算出相差天数
	let day = Math.floor(difValue / (24 * 3600 * 1000));
	// 计算天数后剩余的毫秒数
	let leave1 = difValue % (24 * 3600 * 1000);
	let hour = Math.floor(leave1 / (3600 * 1000));
	let min = Math.floor(difValue / 1000 / 60 % 60);
	let second = Math.floor(difValue / 1000 % 60);
	if (parseInt(hour) < 10) {
    
    
		hour = "0" + hour;
	}
	if (parseInt(min) < 10) {
    
    
		min = "0" + min;
	}
	if (parseInt(second) < 10) {
    
    
		second = "0" + second;
	}
	return day + " 天 " + hour + " 时 " + min + " 分 " + second + " 秒"
}

身份证号码验证

export const isvalidIdCard = (str) => {
    
    
	const reg18 =
		/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
	const reg15 =
		/^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$/;
	return reg18.test(str) || reg15.test(str);
};

手机号验证

export const isvalidPhone = (str) => {
    
    
	const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
	return reg.test(str);
};

大于0并且最多有两位小数

export const maxTwoDecimal = (num) => {
    
    
	const reg = /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/;
	return reg.test(num);
}

以上是我封装的一些辅助方法,后期会继续更新

猜你喜欢

转载自blog.csdn.net/m0_64344940/article/details/125083720
今日推荐