常见正则应用

通过name获取url query参数

const getQueryByName = (name) => { const queryNameRegex = new RegExp(`[?&]${name}=([^&]*)(&|$)`) const queryNameMatch = window.location.search.match(queryNameRegex) // 一般都会通过decodeURIComponent解码处理 return queryNameMatch ? decodeURIComponent(queryNameMatch[1]) : '' }

将字符串首字母转化为大写,剩下为小写
const capitalize = (string) => { const capitalizeRegex = /(?:^|\s+)\w/greturn string.toLowerCase().replace(capitalizeRegex, (match) => match.toUpperCase()) }

将字符串驼峰化
const camelCase = (string) => { const camelCaseRegex = /[-_\s]+(.)?/greturn string.replace(camelCaseRegex, (match, char) => { return char ? char.toUpperCase() : '' }) }

常见手机号处理
手机号码中间四位数字用*表示
const phone = '133123456789' const phoneReg = /^(\d{3})(\d{4})(\d{4})$/ const sphone = phone.replace(phoneReg, '$1--$3')

    推荐阅读