1. 原生js写法

!function () {
    document.getElementById('bankCard').onkeyup = function (event) {
        var v = this.value;
        if (/\S{5}/.test(v)) {
            this.value = v.replace(/\s/g, '').replace(/(.{4})/g, "$1 ");
        }
    };
}();

2. jQuery写法

!function () {
    $('#J_BankCard').on('keyup mouseout input', function () {
        var $this = $(this),
            v = $this.val();
        /\S{5}/.test(v) && $this.val(v.replace(/\s/g, '').replace(/(.{4})/g, "$1 "));
    });
}();

很多人都会写,记下来方便copy。