-2

I'm trying to format on the fly a string containing an American Express card number using a regular expression. It should have the following format 3400 000000 00009. What I found around here is the following:

var ccFmt = ccNum.replace(/\b(\d{4})(\d{6})(\d{5})\b/, '$1-$2-$3');

But this is useful when we have the entire string and we want to transform it. I want to do it on the fly, as the user type in a input field (make a space after first 4 chars, then another space after another 6 chars).

Any ideas how I can handle this ?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
blunthlox
  • 23
  • 4

2 Answers2

1

Is this what you're looking for?

const formatAmex = (input) => input.replace(/\s/g, '').replace(/(\d{4})\s*(\d{6})?\s*(\d{5})?/, '$1 $2 $3').replace(/\s\s/g, ' ').trim()

// tests:
formatAmex('340000000000009')
"3400 000000 00009"
formatAmex('340000000')
"3400 00000"
formatAmex('340')
"340"
formatAmex('3400 000000 00009')
"3400 000000 00009"
formatAmex('340 0 00000 0 00 009')
"3400 000000 00009"
Will
  • 6,601
  • 3
  • 31
  • 42
-1

A library such as jQuery-Mask-Plugin would do this for you.

const $ccInput = $('.cc')
  .mask('0000 000000 00000')
  .val('340000000000000')
  .trigger('input');
  
  console.log($ccInput.data('mask').getCleanVal()); // Raw value
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
<input type="text" class="cc" />

Explanation

Here is what's going on...

const $ccInput = $('.cc');          // Select the element

$ccInput.mask('0000 000000 00000'); // Apply the mask plugin
$ccInput.val('340000000000000');    // Set value
$ccInput.trigger('input');          // Programatically trigger change

$ccInput.val();                     // Masked value
ccInput.data('mask').getCleanVal(); // Raw value

You can make your mask smarter by defining translations.

const $ccInput = $('.cc')
  .mask('XY00 000000 00000', {
    placeholder: '4300 000000 00000',
    translation: {
      'X': { pattern: /4/, optional: false },
      'Y': { pattern: /3/, optional: false }
    }
  })
  .val('432112345612345')
  .trigger('input');
  
  console.log($ccInput.data('mask').getCleanVal()); // Raw value
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
<input type="text" class="cc" />
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132