Insert Spaces Between Card Number Using Jquery

In this tutorial I will show you how to add spaces after every 4 digits of card number using Jquery. Here’s how it can be done. Add a text field on your page.

<input type="text" class="creditCardText" />

Add the following Jquery code on your page. You will need to add some version of jquery for the following code to work.

$('.creditCardText').keyup(function() {
  var foo = $(this).val().split(" ").join(""); // remove hyphens
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1,4}', 'g')).join(" ");

View Demo

This content has been helpful to you?

Thanks for contributing!

Yes No