需求:
一個手機號13152461111,由於安全性,需要替換4-7位字符串為星號,為131****1111,那么有2中玩法,一種是前端隱藏,一種是后台隱藏。
1. 前台隱藏
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mvc1</title>
<script type="text/javascript">
function fn(phone) {
phone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
return phone;
}
console.log('fn', fn('13122222222'));
</script>
</head>
<body>
</body>
</html>
最終效果:
2. 后台隱藏(Java)
// 將手機號碼第4位到第7位替換成*
public class PhoneNuberHide
{
public static void main(String [] args){
String tel = "18753993252";
// 括號表示組,被替換的部分$n表示第n組的內容
tel = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
System.out.print(tel);
}
}
最終效果:
原理解析:
正則表達式中,替換字符串,括號的意思是分組,在replace()方法中,參數二中可以使用$n(n為數字)來依次引用模式串中用括號定義的字串。"(\d{3})\d{4}(\d{4})", "$1***$2"的這個意思就是用括號,分為(前3個數字)中間4個數字(最后4個數字)替換為(第一組數值,保持不變$1)(中間為)(第二組數值,保持不變$2)
@落雨
http://js-dev.cn