校验数字是否有效的11位手机号
function isValidPhoneNum(value: string) {
return /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value)
}
手机号中间4位掩码
function maskPhoneNum(phone: string, space = false) {
if (!phone) {
return ''
}
const reg = /(\d{3})\d{4}(\d{4})/
return phone.replace(reg, space ? '$1 **** $2' : '$1****$2')
}
数字千分位分隔,支持小数点
function thousands(num: number) {
const str = num.toString()
const reg =
str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g
return str.replace(reg, '$1,')
}
URL
获取链接参数,支持query和hash
// 使用 URLSearchParams
function getURLParameter(name: string): string | null {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has(name)) {
return urlParams.get(name);
} else {
const hashParams = new URLSearchParams(window.location.hash.replace('#?', ''));
return hashParams.get(name);
}
}
// 使用正则表达式
function getURLParameter(name: string): string | null {
let match = window.location.search.match(new RegExp('[?&]' + name + '=([^&]+)'));
if (match) {
return decodeURIComponent(match[1]);
} else {
match = window.location.hash.match(new RegExp('[#?&]' + name + '=([^&]+)'));
if (match) {
return decodeURIComponent(match[1]);
}
}
return null;
}
向url拼接查询参数字符串
function appendQuery(url: string, extraQueryParams: Record<string, string | number>, appendPos: 'hash' | 'query' = 'query'): string {
const extraQuery = Object.entries(extraQueryParams)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value.toString())}`)
.join('&');
const [mainPart, hashPart] = url.split('#', 2);
if (appendPos === 'hash' && hashPart) {
const hashQueryIndex = hashPart.indexOf('?');
if (hashQueryIndex >= 0) {
// If there are already query parameters in the hash part, append the new ones
return `${mainPart}#${hashPart.slice(0, hashQueryIndex + 1)}${extraQuery}&${hashPart.slice(hashQueryIndex + 1)}`;
} else {
// If there are no query parameters in the hash part, add the new ones
return `${mainPart}#${hashPart}?${extraQuery}`;
}
} else {
const mainQueryIndex = mainPart.indexOf('?');
if (mainQueryIndex >= 0) {
// If there are already query parameters in the main part, append the new ones
return `${mainPart.slice(0, mainQueryIndex + 1)}${extraQuery}&${mainPart.slice(mainQueryIndex + 1)}`;
} else {
// If there are no query parameters in the main part, add the new ones
return `${mainPart}?${extraQuery}`;
}
}
}
UA
获取iOS的版本
function getIOSVersion() {
const ua = navigator.userAgent
const match = ua.match(/(iPhone\sOS)\s([\d_]+)/)
return match ? match[2].replace(/_/g, '.') : ''
}
function getIOSMajorVersion() {
const version = getIOSVersion()
return version ? parseInt(version, 10) : 0
}