javascript验证手机号和实现星号(*)代替实例
一、JavaScript替换手机号中间4位
//匹配手机号首尾,以类似“123****8901”的形式输出
'12345678901'.replace(/(\d{3})\d{4}(\d{4})/,'$1****$2');
示例
<!doctypehtml>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/>
<title>无标题文档</title>
<scripttype="text/javascript">
varphone='12345678901';
vardh=phone.replace(/(\d{3})\d{4}(\d{4})/,'$1****$2');
alert(dh);
</script>
</head>
<body>
</body>
</html>
注意:此段正则匹配字符串中的连续11位数字,替换中间4位为*号,输出常见的隐匿手机号的格式。如果要仅得到末尾4位,则可以改成如下形式:
二、JavaScript替换手机号前7位
//匹配连续11位数字,并替换其中的前7位为*号
'15110280327'.replace(/\d{7}(\d{4})/,'*******$1');
示例
<!doctypehtml>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/>
<title>无标题文档</title>
<scripttype="text/javascript">
varphone='12345678901';
vardh=phone.replace(/\d{7}(\d{4})/,'*******$1');
alert(dh);
</script>
</head>
<body>
</body>
</html>
补充注释:正则表达式中的括号即可用于分组,同时也用于定义子模式串,在replace()方法中,参数二中可以使用$n(n为数字)来依次引用模式串中用括号定义的字串。
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="UTF-8"/>
<title>js手机号码验证以及隐藏中间四位数字</title>
<scripttype="text/javascript"src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<inputtype="text"id="myText">
<p>js手机验证以及隐藏手机号码中间四位</p>
<inputtype="button"value="提交"id="subBtn">
<scripttype='text/javascript'>
$(function(){
$("#subBtn").click(function(){
if($("#myText").val()==""){
alert("手机号码不能为空")
}else{
if(iphoneCheck(myText)){
alert("提交成功");
varphone=$("#myText").val();
varmyphone=phone.substr(3,4);
//alert(myphone)
varlphone=phone.replace(myphone,"****");
$("#myText").val(lphone);
}else{
alert("请输入正确的手机号码")
}
}
functioniphoneCheck(id){
vartemp=document.getElementById("myText");
varre=/^[1][34587]\d{9}$/;//手机号码验证正则表达式
if(re.test(temp.value)){
returntrue;
}else{
returnfalse;
}
}
});
});
</script>
</body>
</html>
总结
以上就是javascript验证手机号与实现星号(*)代替效果的全部内容,希望本文的内容对大家日常使用JavaScript能有所帮助。