// 保留首尾,輸出形如 123****8901
'12345678901'.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
完整可運行範例:
<!doctype html>
<html xmlns="https://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 位數字,把中間四位換成星號,得到最常見的遮罩格式。
// 把前 7 位換成星號
'15110280327'.replace(/\d{7}(\d{4})/, '*******$1');
<!doctype html>
<html xmlns="https://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 依序引用括號裡捕獲到的字串。
實務上表單通常需要「先驗證格式、再遮罩顯示」,兩件事一起做:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>js手機號碼驗證以及隱藏中間四位數字</title>
<script type="text/javascript" src="https://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()) {
alert("提交成功");
var phone = $("#myText").val();
var myphone = phone.substr(3, 4);
var lphone = phone.replace(myphone, "****");
$("#myText").val(lphone);
} else {
alert("請輸入正確的手機號碼");
}
}
});
function iphoneCheck() {
var temp = document.getElementById("myText");
var re = /^[1][34587]\d{9}$/; // 手機號碼驗證正則
return re.test(temp.value);
}
});
</script>
</body>
</html>
小結:正則替換負責遮罩,test() 負責格式校驗,兩者搭配就能應付絕大多數手機號欄位的需求。若追求更好相容性與可讀性,也可以考慮 input[type=tel] 搭配 maxlength 一併處理。