Skip to content

Instantly share code, notes, and snippets.

@kevindees
Created October 24, 2016 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevindees/ae2b1b838444bf82d1af2db4d627d036 to your computer and use it in GitHub Desktop.
Save kevindees/ae2b1b838444bf82d1af2db4d627d036 to your computer and use it in GitHub Desktop.
function spaceCard(str) {
var ret = [];
var i;
var len;
str = str.replace(/\s|\D+/gi, '');
if( str.match(/^3[47]/) ) {
// american express only
var sec = 4;
for(i = 0, len = str.length; i < len; i+= sec) {
switch(i) {
case 4:
sec = 6;
break;
case 10:
sec = 5;
break;
}
ret.push(str.substr(i, sec))
}
} else {
// group by four
for(i = 0, len = str.length; i < len; i += 4) {
ret.push(str.substr(i, 4))
}
}
return ret.join(' ');
}
$('#card-number').on('keyup', function() {
var $el = $(this);
$el.val( spaceCard($el.val()) );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment