做專案,自己實現的一些常用的JS方法
一、判斷url
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g;
export function isUrl(path) {
return reg.test(path);
}
複製程式碼
二、url獲取引數
export default class WebUtils {
static getParamFromQueryString(key) {
const queryString = window.location.search;
if (queryString) {
const reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`, 'i');
const r = queryString.substr(1).match(reg);
if (r !== null) return r[2];
}
return null;
}
}
複製程式碼
三、正則實用判斷
export default class CheckUtils {
static checkMobile(mobile) { // 檢測手機
return /^1[3|4|5|7|8]\d{9}$/.test(mobile);
}
static checkInt(num) { // 正整數
return /^0|([1-9]\d*)\b/.test(mobile);
}
static checkEmail(email) {
return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email);
}
static isEmail(email) {
return /^\w+([-+.]\w+)*@163.com.cn$/.test(email);
}
static checkQQ(qq) {
return /^\d{5,}$/.test(qq) || CheckUtils.checkEmail(qq);
}
static checkWechat(wx) {
return CheckUtils.checkMobile(wx) || CheckUtils.checkEmail(wx) || CheckUtils.checkQQ(wx) || /^[a-zA-Z\d_]{5,}$/.test(wx);
}
static checkSmsCode(smsCode) {
return /\d{6}/.test(smsCode);
}
static checkIdentityCode(identityCode) {
return /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/.test(identityCode);
}
static checkName(name) {
return /^[\u0391-\uFFE5A-Za-z0-9]+$/.test(name);
}
static checkPostCode(name) {
return /^[1-9][0-9]{5}$/.test(name);
}
static numtoFixed(num) { // 千分位設定
if (typeof num !== 'number') {
return num;
}
let b = null;
if (num.toString().indexOf('.') === -1) {
b = (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
} else {
b = num.toString().replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
}
return b;
}
static twonumCheck(num) { // 千分位設定
return /^\d+(\.\d{1,2})?$/.test(num);
}
}
複製程式碼
四、節流sleep、關閉當前頁面
/*
* 等待函式 sleep
* @param time 要獲取的引數time
* sleep(5000).then(() => {
console.log('業務程式碼')
})
*/
export function sleep(time) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
/*
* 關閉當前頁面 closePage
*/
export function closePage() {
const { userAgent } = navigator;
if (userAgent.indexOf('Firefox') !== -1 || userAgent.indexOf('Chrome') !== -1) {
window.history.back();
window.close();
} else if (userAgent.indexOf('Android') > -1 || userAgent.indexOf('Linux') > -1) {
window.history.back();
window.close();
} else {
window.opener = null;
window.close();
}
}
複製程式碼