So these are some of the encapsulation methods that were used in the project, so be open to questions.
Verify the regular phone number
function isMobile (mobile) {
return /^1[3-9]\d{9}$/.test(mobile)
}
Copy the code
Intercepts URL parameters
function getQueryObject(url) {
url = url == null ? window.location.href : url
const search = url.substring(url.lastIndexOf('? ') + 1)
const obj = {}
const reg = /([^?&=]+)=([^?&=]*)/g
search.replace(reg, (rs, $1, $2) = > {
const name = decodeURIComponent($1)
let val = decodeURIComponent($2)
val = String(val)
obj[name] = val
return rs
})
return obj
}
getQueryObject('https//www.baidu.com?id=1111&type=edit')
Copy the code
Formatting time (Method 1)
function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/ ^ [0-9] + $/.test(time))) {
time = parseInt(time)
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1.d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g.(result, key) = > {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') { return ['day'.'一'.'二'.'三'.'four'.'five'.'六'][value] }
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
/ / use
parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}')
Copy the code
Formatting time (Method 2)
/** * Format time */
function NewTime(time) {
if(! time) time =new Date(a)const t = new Date(time) // The time you know
t.setTime(t.setMinutes(t.getMinutes())) // Set the new time to one minute longer than the old time
const Y = t.getFullYear()
let M = t.getMonth() + 1
let D = t.getDate()
let HH = t.getHours()
let MM = t.getMinutes()
let SS = t.getSeconds()
if (M < 10) M = '0' + M
if (D < 10) D = '0' + D
if (HH < 10) HH = '0' + HH
if (MM < 10) MM = '0' + MM
if (SS < 10) SS = '0' + SS
// let date_value = Y + '-' + M + '-' + D + ' ' + HH + ':' + MM + ':' + SS;
const date_value = Y + The '-' + M + The '-' + D + ' ' + HH + ':' + MM + ':' + SS
return date_value
}
Copy the code
Store, obtain, and delete sessionStorage
function __setItem(name, content) {
if(! name)return;
if (typeofcontent ! = ='string') {
content = JSON.stringify(content);
}
window.sessionStorage.setItem(name, content);
};
function __getItem(name) {
if(! name)return;
return window.sessionStorage.getItem(name);
};
function __removeItem(name) {
if(! name)return;
window.sessionStorage.removeItem(name);
};
Copy the code
Detection mobile phone Number
function _isMobile(mobile) {
var reg = ,4,5,7,8 / ^ [1] [3] [0-9] {9} $/;
if (reg.test(mobile)) return true;
else return false;
};
Copy the code
Convert Base64 to a file
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(', '), mime = arr[0].match(/ : (. *?) ; /) [1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
}
Copy the code
Replace the middle four digits of the phone number
function replacePhone(num) {
let mphone = num;
if (_isMobile(num)) {
mphone = num.substr(0.3) + '* * * *' + num.substr(7);
}
return mphone;
};
Copy the code
Remove whitespace from content
function deblank(str) {
str = str.replace(/\s*/g.' ');
return str;
};
Copy the code
The phone number format is 344
function phoneSeparated(num) {
let mphone = num;
if (_isMobile(num)) {
mphone =
num.substring(0.3) +
' ' +
num.substring(3.7) +
' ' +
num.substring(7.11);
}
return mphone;
};
Copy the code
Card format 4444 replacement
function cardSeparated(num) {
let index = num ? num.length / 4 : 0;
let result = ' ';
for (let i = 0; i < index; i++) {
result += num.substring(i * 4, (i + 1) * 4) + ' ';
}
return result;
};
Copy the code
Id card format birthday replacement
function identityCardSeparated(num) {
if (num.length === 18) {
var str = num.substr(0.6) + '* * * * * * * *' + num.substr(14);
return str;
} else {
returnnum; }};Copy the code
Replacement of passport Number
function passportSeparated(num) {
if (num.length > 4) {
var str = num.substr(0, num.length - 4) + '* * * *';
return str;
} else {
returnnum; }};Copy the code
Add short lines every four digits to the card number
function cardNoFormat(cardNo) {
if (typeof cardNo == 'number') {
cardNo = String(cardNo).replace(/\D/g.' ').replace(/... (? ! $)/g.'$& -);
} else {
cardNo = cardNo.replace(/\D/g.' ').replace(/... (? ! $)/g.'$& -);
}
return cardNo;
};
console.log(cardNoFormat('124141251512'))
console.log(cardNoFormat(1233124124124124))
Copy the code
Simple deep copy deepClone
function deepClone(data) {
if(! data &&typeofdata ! = ='object') {
throw new Error('error arguments'.'deepClone')}const obj = data.constructor === Array ? [] : {}
Object.keys(data).forEach(keys= > {
if (data[keys] && typeof data[keys] === 'object') {
obj[keys] = deepClone(data[keys])
} else {
obj[keys] = data[keys]
}
})
return obj
}
var arr = [1.2.3.4.5.6];
console.log(deepClone(arr))
arr = [...arr, ...[7.8.9]]
console.log(arr, 'arr')
Copy the code
Add Spaces every four digits
function fourSpace(num) {
var value = num
.replace(/\D/g.' ')
.replace(/... (? ! $)/g.'$&');
return value;
};
fourSpace('13122223333')
Copy the code
Verification of identity card
function IdentityCodeValid(code) {
let city = {
11: 'Beijing'.12: 'tianjin'.13: 'hebei'.14: 'the shanxi'.15: Inner Mongolia.21: 'the liaoning'.22: 'jilin'.23: 'Heilongjiang'.31: 'Shanghai'.32: 'jiangsu'.33: 'zhejiang'.34: 'anhui'.35: 'fujian'.36: 'jiangxi'.37: 'shandong'.41: 'henan'.42: 'hubei'.43: 'in hunan province'.44: 'in guangdong'.45: 'the guangxi'.46: 'hainan'.50: 'chongqing'.51: 'sichuan'.52: 'guizhou'.53: 'yunnan'.54: 'Tibet'.61: 'the shaanxi'.62: 'gansu'.63: 'the qinghai'.64: 'the ningxia'.65: 'the xinjiang'.71: 'Taiwan'.81: 'Hong Kong'.82: 'the'.91: 'foreign'
};
let tip = ' ';
let pass = true;
if(! code || !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)) {
tip = 'Wrong format of ID number';
pass = false;
} else if(! city[code.substr(0.2)]) {
tip = 'Address code error';
pass = false;
}
if(! pass) message.error(tip);return pass;
};
Copy the code
HmacSHA256 encryption
function encryptHmacSHA256(value) {
const userInfo = getUserInfo();
let key = ' ';
if (userInfo.data) {
key = userInfo.data.publicKey;
}
let ciphertext = CryptoJS.HmacSHA256(value, key);
let hashInBase64 = CryptoJS.enc.Base64.stringify(ciphertext);
return hashInBase64;
};
Copy the code
Object is converted to an empty string
function _replaceNull(obj) {
if (typeof obj === 'object') {
Object.keys(obj).forEach(element= > {
let value = obj[element];
if (value === null || value === undefined) {
// obj[element] = '';
delete obj[element];
} else if (typeof value === 'object') { _replaceNull(value); }}); }return obj;
};
Copy the code
File export
function _checkoutFile(fileName, response) {
console.log('response');
console.log(response);
let blob = new Blob([response], { type: 'application/vnd.ms-excel' });
let objectUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.setAttribute('href', objectUrl);
a.setAttribute('download', fileName);
a.click();
URL.revokeObjectURL(objectUrl);
};
Copy the code
Url File Export
function _urlExportFile(url) {
const a = document.createElement('a');
a.setAttribute('href', url);
a.click();
};
Copy the code
Url check
function validateURL(url, list) {
let i = 0;
if (list) {
list.forEach(el= > {
if (url === el) {
i = 1; }}); }if(i ! = =0) return false;
if (i === 0) return true;
};
Copy the code
Page visible height, page visible width
function clientHeight() {
let clientHeight = document.getElementById('root').clientHeight;
let offsetHeight = document.getElementById('root').offsetHeight;
return clientHeight || offsetHeight;
};
function clientWidth() {
let clientWidth = document.getElementById('root').clientWidth;
let offsetWidth = document.getElementById('root').offsetWidth;
return clientWidth || offsetWidth;
};
Copy the code
Formatted amount
function formatMoney(val) {
var valStr = String(Number(val).toFixed());
var prefix_val, suffix_val, prefix_result, prefix_arr = null;
var j, t, i = 0;
let negativeFlag = false; / / negative
if (isNaN(Number(valStr))) {
return val
}
if(Number(valStr) < 0){
negativeFlag = true;
valStr = String(Math.abs(valStr))
}
if (valStr.length < 3) {
valStr = prefix(valStr, 3)
}
prefix_val = valStr.slice(0, -2)
suffix_val = valStr.slice(-2)
prefix_result = []
prefix_arr = prefix_val.split("")
j = 0
t = 3
for (i = prefix_arr.length - 1; i >= 0; i--) {
j++
if (j === t || i === 0) {
prefix_result.unshift(prefix_arr.splice(i).join(""))
j = 0}}if(negativeFlag){
return The '-' + prefix_result.join(",") + "." + suffix_val
}else{
return prefix_result.join(",") + "." + suffix_val
}
}
formatMoney(1111111)
Copy the code