银行账号每4位插入一个空格

<!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></head><body><input type="text" id="kahao" /><script>$(function() {$('#kahao').on('keyup', function(e) {//只对输入数字时进行处理if((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105 )){//获取当前光标的位置var caret = this.selectionStart//获取当前的valuevar value = this.value//从左边沿到坐标之间的空格数var sp = (value.slice(0, caret).match(/\s/g) || []).length//去掉所有空格var nospace = value.replace(/\s/g, '') //重新插入空格var curVal = this.value = nospace.replace(/(\d{4})/g, "$1 ").trim() //从左边沿到原坐标之间的空格数var curSp = (curVal.slice(0, caret).match(/\s/g) || []).length//修正光标位置this.selectionEnd = this.selectionStart = caret + curSp - sp }}) }) </script></body></html>

posted @ 2017-05-27 13:56  伪猿123  阅读(609)  评论(0编辑  收藏  举报