<html>
<style>
.idCard {500px;}
</style>
<body>
<input type="text" id="idCard" onkeyup="this.value=filterNum(this.value)" onafterpaste="this.value=filterNum(this.value)" maxlength="23">
</body>
<script>
function filterNum(str){
//过滤非数字获得一个新的字符串
//验证字符串数字长度
//str='1234234 34534'
str=str.replace(/D/g,'');
if(str.length>19){
str = str.substr(0,19);
}
return initNum(str);
}
function initNum( num ){
if( typeof num == "undefined"){
return ;
}
if(/S{5}/.test(num)){
num = num.replace(/s/g, '').replace(/(.{4})/g, "$1 ");
if(num.replace(/s/g,'').length%4==0){
num=num.substr(0,num.length-1);
}
}
return num
}
</script>
</html>