一、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能有所幫助。
新聞熱點
疑難解答