常用正则
1. 数字价格千分位分割
'123456789'.replace(/(?!^)(?=(\d{3})+$)/g, ',') // 123,456,789
小数千分位支持
const formatNum = numStr => {
const regex = new RegExp(`(?!^)(?=(\\d{3})+${numStr.includes('.') ? '\\.' : '$'})`,'g')
return numStr.replace(regex,',')
}
console.log(formatNum('123456789.123456')); // 123,456,789.123456
2. 手机号3-4-4分割
console.log('18379836654'.replace(/(?=(\d{4})+$)/g, '-')) // 183-7983-6654
扩展
-
123 => 123
-
1234 => 123-4
-
12345 => 123-45
-
123456 => 123-456
-
1234567 => 123-4567
-
12345678 => 123-4567-8
-
123456789 => 123-4567-89
-
12345678911 => 123-4567-8911
想想这其实是我们经常遇到的用户输入手机号的过程中,需要不断格式化。
const formatMobile = mobile => {
return String(mobile).slice(0,11)
.replace(/(?<=\d{3})\d+/, ($0) => '-' + $0)
.replace(/(?<=[\d-]{8})\d{1,4}/, ($0) => '-' + $0)
}
console.log(formatMobile(18379836654)) // 183-7983-6654
3. 验证密码的合法性
密码长度是6-12位,由数字、小写字母和大写字母组成,但必须至少包括2种字符
let reg = /((?=.*\d)((?=.*[a-z])|(?=.*[A-Z])))|(?=.*[a-z])(?=.*[A-Z])^[a-zA-Z\d]{6,12}$/
console.log(reg.test('123456')) // false
console.log(reg.test('aaaaaa')) // false
console.log(reg.test('AAAAAAA')) // false
console.log(reg.test('1a1a1a')) // true
console.log(reg.test('1A1A1A')) // true
console.log(reg.test('aAaAaA')) // true
console.log(reg.test('1aA1aA1aA')) // true
4. 提取连续重复的字符
将有重复的字符提取出来,例如12323454545666,提取[ ‘23’, ‘45’, ‘6’ ]
const collectRepeatStr = (str) => {
let repeatStrs = []
const repeatRe = /(.+)\1+/g
str.replace(repeatRe, ($0, $1) => {
$1 && repeatStrs.push($1)
})
return repeatStrs
}
console.log(collectRepeatStr('12323454545666')) // ["23", "45", "6"]
5. 实现一个trim函数
去除字符串的首尾空格
// 去除空格法
const trim = (str) => {
return str.replace(/^\s*|\s*$/g, '')
}
// 提取非空格法
const trim = (str) => {
return str.replace(/^\s*(.*?)\s*$/g, '$1')
}
6. HTML转义
防止XSS攻击的方式之一就是做HTML转义,转义规则如下,要求将对应字符转换成等值的实体。而反转义则是将转义后的实体转换为对应的字符
const escape = (string) => {
const escapeMaps = {
'&': 'amp',
'<': 'lt',
'>': 'gt',
'"': 'quot',
"'": '#39'
}
// 这里和/[&<>"']/g的效果是一样的
const escapeRegexp = new RegExp(`[${Object.keys(escapeMaps).join('')}]`, 'g')
return string.replace(escapeRegexp, (match) => `&${escapeMaps[match]};`)
}
console.log(escape(`
<div>
<p>hello world</p>
</div>
`))
7. HTML反转义
const unescape = (string) => {
const unescapeMaps = {
'amp': '&',
'lt': '<',
'gt': '>',
'quot': '"',
'#39': "'"
}
const unescapeRegexp = /&([^;]+);/g
return string.replace(unescapeRegexp, (match, unescapeKey) => {
return unescapeMaps[ unescapeKey ] || match
})
}
console.log(unescape(`
<div>
<p>hello world</p>
</div>
`))
8. 将字符串驼峰化
const camelCase = (string) => {
const camelCaseRegex = /[-_\s]+(.)?/g
return string.replace(camelCaseRegex, (match, char) => {
return char ? char.toUpperCase() : ''
})
}
console.log('foo-bar') // fooBar
console.log('foo_bar') // fooBar
9. 将字符串首字母转化为大写,剩下为小写
例如 hello world 转为为Hello World
const capitalize = (string) => {
const capitalizeRegex = /(?:^|\s+)\w/g
return string.toLowerCase().replace(capitalizeRegex, (match) => match.toUpperCase())
}
console.log(capitalize('hello world')) // Hello World
console.log(capitalize('hello WORLD')) // Hello World
10. 获取网页中所有img标签的图片地址
要求必须是在线链接 例如
https://xxx.juejin.com/a.jpg、http://xxx.juejin.com/a.jpg、//xxx.juejjin.com/a.jpg
const matchImgs = (sHtml) => {
const imgUrlRegex = /<img[^>]+src="((?:https?:)?\/\/[^"]+)"[^>]*?>/gi
let matchImgUrls = []
sHtml.replace(imgUrlRegex, (match, $1) => {
$1 && matchImgUrls.push($1)
})
return matchImgUrls
}
11. 匹配24小时制时间
判断时间time是否符合24小时制
const check24TimeRegexp = /^(?:[01]\d|2[0-3]):[0-5]\d$/
console.log(check24TimeRegexp.test('01:14')) // true
console.log(check24TimeRegexp.test('23:59')) // true
console.log(check24TimeRegexp.test('23:60')) // false
console.log(check24TimeRegexp.test('1:14')) // false
console.log(check24TimeRegexp.test('1:1')) // false
12. 匹配手机号
检测一个字符串是否符合手机号的规则
const mobileRegex = /^(?:\+?86)?1(?:3\d{3}|5[^4\D]\d{2}|8\d{3}|7(?:[235-8]\d{2}|4(?:0\d|1[0-2]|9\d))|9[0-35-9]\d{2}|66\d{2})\d{6}$/
console.log(mobileRegex.test('18379867725')) // true
console.log(mobileRegex.test('123456789101')) // false
console.log(mobileRegex.test('+8618379867725')) // true
console.log(mobileRegex.test('8618379867725')) // true
821

被折叠的 条评论
为什么被折叠?



