js 手机号实现(344) 下面有将正则验证去掉“-” 或“空格”
<!DOCTYPE html> <head> <meta charset="UTF-8"> <title>aaa</title> </head> <body> <input type="tel" id="phone" onfocus="getCursortPosition(this);" onclick="getCursortPosition(this);" onkeyup="format(this);" maxlength="13"/> <script> var CaretPos = -1; var numLength = 0; function valid(value){ if(value && !/^\d{0,25}$/g.test(value)){ return value.replace(/[^0-9]/ig, ‘‘); } return value; } function format(obj){ var value=valid(obj.value); value=value.replace(/\s*/g,""); var result=[]; for(var i=0;i<value.length;i++){ if(i==3 || i==7){ result.push("-"+value.charAt(i)); //双引号里减号 可替换 }else{ result.push(value.charAt(i)); } } obj.value=result.join(""); if(obj.value.length < numLength){ if(CaretPos == 10 || CaretPos == 5){ CaretPos -= 2; } else { CaretPos -= 1; } setCaretPosition(obj, CaretPos); } console.log(CaretPos); if(obj.value.length > numLength){ if(CaretPos == 8 || CaretPos == 3){ CaretPos += 2; } else { CaretPos += 1; } setCaretPosition(obj, CaretPos); } numLength = obj.value.length; } function getCursortPosition (ctrl) { if (document.selection) { ctrl.focus (); var Sel = document.selection.createRange(); Sel.moveStart (‘character‘, -ctrl.value.length); CaretPos = Sel.text.length; }else if (ctrl.selectionStart || ctrl.selectionStart == ‘0‘) CaretPos = ctrl.selectionStart; } function setCaretPosition(ctrl, pos){ if(ctrl.setSelectionRange) { ctrl.focus(); ctrl.setSelectionRange(pos,pos); } else if (ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true); range.moveEnd(‘character‘, pos); range.moveStart(‘character‘, pos); range.select(); } } </script> </body>
jq 实现银行卡没四个数加一个空格 下面有将正则验证去掉“-” 或“空格”
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>银行卡号4位空格</title> <script src="http://j2.58cdn.com.cn/js/jquery-1.8.3.js"></script><!--依赖jquery--> </head> <body> <input type="tel" placeholder="请输入储蓄卡卡号" name="cardNum"> <script> //监控input事件 document.querySelector(‘input[name=cardNum]‘).addEventListener(‘input‘, function() { //获取当前光标位置 var position = this.selectionStart; var v = this.value; //四个字符加一个空格 this.value = v.replace(/\s/g, ‘‘).replace(/(.{4})/g, "$1 "); //优化语句:如果当前位置是空格字符,则自动清除掉 if (this.value.charAt(this.value.length - 1) == ‘ ‘) { this.value = this.value.substring(0, this.value.length - 1); } var input = this; //重新定位光标位置,start和end都需要设置,不然就是截取片段了 //countSpace此方法报错,但是不影响使用,我也没解决问题所在,求大神 input.selectionStart = position + countSpace(this.value, position); input.selectionEnd = position + countSpace(this.value, position); }) </script> </body> </html>
用正则验证去掉“-” 或“空格”
<html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <script type="text/javascript"> var str="187-5332 5214+1000"; // 假如这是你得到的字符串 // 下面进行替换 var str_rep = str.replace(/\+|\-|\s+|\*|\?/g,""); console.log(str_rep); // 不知道是不是你所说的那样 </script> </head> </html>