js用面向对象实现给手机号中间4位数打*号
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
window.onload = function(){
// var str = '13014039091';
// var reg = /(\d{3})(\d{4})(\d{4})/g;
// console.log(str.replace(reg,'$1****$3'));
//普通方法
// var pt = document.querySelector('input');
// var btn = document.querySelector('button');
// var p = document.querySelector('p');
// btn.onclick = function(){
// var reg = /^(\d{3})(\d{4})(\d{4})$/g;
// var txt = pt.value;
// p.innerText = txt.replace(reg,'$1****$3');
// }
// 面向对象
function Phone(){
this.pt = document.querySelector('input');
this.btn = document.querySelector('button');
this.p = document.querySelector('p');
//替换
this.init();
}
Phone.prototype.init = function(){
var that = this;
this.btn.onclick = function(){
var str = that.pt.value.trim();
var reg = /(\d{3})(\d{4})(\d{4})/g;
var ph = /^1\d{10}$/;
if(!(ph.test(str))){
alert('输入正确手机号');
return false;
}
that.p.innerText = str.replace(reg,'$1****$3');
}
}
new Phone();
}
</script>
</head>
<body>
<input type="text" placeholder="输入手机号" maxlength="11"/>
<button type="button">确定</button>
<p></p>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634757.html