一、JavaScript替换手机号中间4位
// 匹配手机号首尾,以类似“123****8901”的形式输出 \'12345678901\'.replace(/(\\d{3})\\d{4}(\\d{4})/, \'$1****$2\');
示例
<!doctype html> <html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" /> <title>无标题文档</title> <script type=\"text/javascript\"> var phone=\'12345678901\'; var dh=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\');
示例
<!doctype html> <html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" /> <title>无标题文档</title> <script type=\"text/javascript\"> var phone=\'12345678901\'; var dh=phone.replace(/\\d{7}(\\d{4})/, \'*******$1\'); alert (dh); </script> </head> <body> </body> </html>
补充注释:正则表达式中的括号即可用于分组,同时也用于定义子模式串,在replace()方法中,参数二中可以使用$n(n为数字)来依次引用模式串中用括号定义的字串。
三、JavaScript手机验证以及隐藏手机号码中间四位综合实例
<!doctype html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <title>js手机号码验证以及隐藏中间四位数字</title> <script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-latest.js\"></script> </head> <body> <input type=\"text\" id=\"myText\"> <p>js手机验证以及隐藏手机号码中间四位</p> <input type=\"button\" value=\"提交\" id=\"subBtn\"> <script type=\'text/javascript\'> $(function(){ $(\"#subBtn\").click(function(){ if($(\"#myText\").val()==\"\"){ alert(\"手机号码不能为空\") }else{ if(iphoneCheck(myText)){ alert(\"提交成功\"); var phone=$(\"#myText\").val(); var myphone=phone.substr(3,4); //alert(myphone) var lphone=phone.replace(myphone,\"****\"); $(\"#myText\").val(lphone); }else{ alert(\"请输入正确的手机号码\") } } function iphoneCheck(id){ var temp=document.getElementById(\"myText\"); var re=/^[1][34587]\\d{9}$/;//手机号码验证正则表达式 if(re.test(temp.value)){ return true; }else{ return false; } } }); }); </script> </body> </html>
总结
以上就是javascript验证手机号与实现星号(*)代替效果的全部内容,希望本文的内容对大家日常使用JavaScript能有所帮助。
本文地址:https://www.stayed.cn/item/23583
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我