正则表达式
提取
//提取所有的数字
let str = "中国移动:10086,中国联通:10010,中国电信:10000"
console.log(str.match(/\d{5}/g)) //array
//提取电话号码
let hd = `张三:010-5555555,李四:010-66666666`
let number = hd.match(/\d{3}-\d{7,8}/g)
let name = hd.match(/[^:-\d,\s]+/g) //只要名字
//提取日期
let str = '2017-11-12'
let array = str.match(/(\d{4})[-](\d{2})[-](\d{2})/g)
console.log(RegExp.$3) //12
//提取用户名/邮箱
let email = 'woaiyinle520@'
email.match(/([0-9a-zA-Z_.-]+)[@]([0-9a-zA-Z_.-]+)(([.][a-zA-Z]+){1,2})/)
console.log(RegExp.$1) //woaiyinle520
replace替换
let str = '你好,我很好'
console.log(str.replace(/好/g, '帅')) //你帅,我更帅
//去空字符串
//去除两头空字符
let str = " 哈哈 ,你好 呵呵 "
console.log(str.trim()) //"哈哈 ,你好 呵呵"
//去除全部空字符
let str = " 哈哈 ,你好 呵呵 "
console.log(str.replace(/\s+/g, '')) //'哈哈,你好呵呵'
//h替换成S
let str = 'HhpphH'
console.log(str.replace(/[h]/ig, 'S')) //SSppSS
匹配任何字符
let num = 'sdfs88jj77'
console.log(num.match(/[\d\D]+/g)) //["sdfs88jj77"]
获取所有内容:空格也要
let str = ' sdfs88j j77 '
console.log(str.match(/[\s\S]+/)[0]) //' sdfs88j j77 '
匹配0-100的数字
//不能有空格
^(\d{1,2}|100)$
^(\d{1,2}(\.\d{1,2})?|100|100.0|100.00)$
身份证
//15位或者18位
([1-9][0-9]{14})|([1-9][0-9]{16}[0-9xX])
//15位或者18位
([1-9][0-9]{14})([0-9]{2}[0-9xX])?
//如果后面括号出现0次是15位,出现1次是18位,精妙!
号码
//座机号码的正则表达式
010-19876754
0431-87123490
[0-9]{3,4}[-][0-9]{8}
\d{3,4}[-]\d{8}
\d{3,4}[-][0-9]{8}
//qq号码的正则表达式
[1-9][0-9]{4,10}
\d{5,12}
//手机号码的正则表达式
130 131 132 133 134 135 136 137 138 139
143 147
150 151 152 153 154 155 156 157 158 159
170 171 173 176 177
180 181 182 183 184 185 186 187 188 189
([1][358][0-9][0-9]{8})|([1][4][37][0-9]{8})|([1][7][01367][0-9]{8})
邮政编码
/^\d{6}$/
邮箱
woaiyinle520@163.com
woaiyinle520@gmail.com.cn
[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}
密码
字母开头,后面字母数字下划线,长度5-30
/^[a-zA-Z]\w{5,29}$/
密码强度
function getLvl(pwd) {
let lvl = 0 //默认是0级
//密码中是否有数字,或者是字母,或者是特殊符号
if (/[0-9]/.test(pwd)) {
lvl++
}
//判断密码中有没有字母
if (/[a-zA-Z]/.test(pwd)) {
lvl++
}
//判断密码中有没有特殊符号
if (/[^0-9a-zA-Z_]/.test(pwd)) {
lvl++
}
return lvl //最小的值是1,最大值是3
}
验证邮箱
document.getElementById("email").onblur = function () {
//判断这个文本框中输入的是不是邮箱
var reg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/;
if (reg.test(this.value)) {
this.style.backgroundColor = "green";
} else {
this.style.backgroundColor = "red";
}
}