一、备选字符集
var str ="上海,上天,上哪里去";
var reg =/上[海天]/g
console.log(str.replace(reg,"*")); // *,*,上哪里去
var reg = /[上天哪]/g
var str = "上海,上天,上哪里"
console.log(str.replace(reg,"*")); // *海,**,**里
var str = "我去,我草,你这游戏打的太牛逼了"
var reg = /[去草]|牛逼/g
console.log(str.replace(reg,"*")); // 我*,我*,你这游戏打的太*了
var res = "ajkdgkbcj128973489"
var reg = /[0-9]/g
console.log(res.replace(reg,"*")); // ajkdgkbcj*********
var str = "hello"
var reg = /[el]o/g
console.log(str.replace(reg,"*")); // hel*
二、转义字符
var str = "https://www.baidu.com"
var str2 = "http://www.baidu.com"
var reg = /(http|https):\/\/[w]{3}\.baidu\.com/
console.log(reg.test(str));
console.log(reg.test(str2));
三、指定匹配的位置
// 电话
var num = "13897932473123"
var reg = /^1[3-9]\d{9}$/
console.log(reg.test(num));
<input type="text" id="input">
<script>
/* 去除开头结尾的空格 */
var res = []
var reg = /^\s+|\s+$/g;
var input = document.getElementById("input")
input.onkeydown = function(event){
if(event.keyCode == 13){
var str = this.value
res.push(str.replace(reg,""))
console.log(res);
}
}
</script>
四、非
var str = "hello210874"
var reg = /[^a-z]/g
console.log(str.replace(reg,"")); // hello
var str = "<p>我是p标签</p>。<div>我是div</div>"
var reg = /<[^<>]+>/g
console.log(str.replace(reg,"")); // 我是p标签。我是div
var str = "https://movie.douban.com/subject/1292052/"
var reg = /[^\d+]/g
console.log(str.replace(reg,"")); // 1292052
五、邮箱验证
<input type="text" id="email" placeholder="请输入邮箱">
<script>
var e=document.getElementById("email")
e.onkeyup=function(event){
if(event.keyCode==13){
var value=this.value.trim();
var reg=/^[\w]+@[0-9a-z]+\.[a-z]+$/;
console.log(reg.test(value))
}
}
</script>
六、密码验证
<input type="password" id="email" placeholder="请输入密码">
<script>
var e=document.getElementById("email")
e.onkeyup=function(event){
if(event.keyCode==13){
var value=this.value.trim();
// 输入六位数密码
var reg=/^\d{6}$/;
console.log(reg.test(value))
}
}
</script>
七、账户密码
<input type="password" id="email" placeholder="请输入密码">
<script>
var e=document.getElementById("email")
e.onkeyup=function(event){
if(event.keyCode==13){
var value=this.value.trim();
// 以字母开头,后面是数字,数字至少包含5位
var reg=/^[a-zA-Z]+\d{5,}$/;
console.log(reg.test(value))
}
}
</script>
八、用户名验证
<input type="text" id="email" placeholder="请输入用户名">
<script>
var e=document.getElementById("email")
e.onkeyup=function(event){
if(event.keyCode==13){
var value=this.value.trim();
var reg=/^[a-zA-Z]{1,8}$/;
console.log(reg.test(value))
}
}