How to add letter-spacing after every 4 digits of a credit card in HTML using JavaScript

How to add letter-spacing after every 4 digits of credit card in HTML using JavaScript

It is always a good practice to mask input text boxes for standardizing data in various formats. In this article, we will see how to add letter-spacing after every 4 digits of a credit card in HTML using JavaScript.

One of the hot topics in masking input text boxes is for masking credit card numbers. The credit card, master card, visa card, union card, etc. have their format for having space after every 4 digits. We can achieve a space after every 4 digits using JavaScript.

Let’s first see how a credit card number looks without masking:

credit-card-without-spacing
Card number without spacing

Here you will notice that it is a bit difficult to read such 16 digits without masking. With the following simple JavaScript snippet, we can add masking to our input and letter-spacing after every 4 digits of a credit card:

Table of Contents

HTML

Let’s write an input text type field that will take the card number. This field can also be a field for a Stripe or any other payment processing service.

<input type="text" size="20" autocomplete="off" class="form-control" id="number" required />

JavaScript

Let’s target the input field using the ID. We need to define a keyup event so that when a number is typed, the script may execute.

// target the input field by ID and assign keyup event
$('#number').on('keyup', function(e){
    // get value of the input field
    var val = $(this).val();
    var newval = '';
    // write regex to remove any space
    val = val.replace(/\s/g, '');
    // iterate through each numver
    for(var i = 0; i < val.length; i++) {
        // add space if modulus of 4 is 0
        if(i%4 == 0 && i > 0) newval = newval.concat(' ');
        // concatenate the new value
        newval = newval.concat(val[i]);
    }
    // update the final value in the html input
    $(this).val(newval);
});

The above script will iterate through each number and add a character space after every 4 digits.

After applying the above script, we will get masking as below:

credit-card-with-spacing
Card number with spacing

Now, you will notice that the numbers are easy to read and in a format that a payment processing card normally has.

Related Posts