<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>银行卡四位空格</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
</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
var 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>