Home > Enterprise >  How to add space between every 4 numbers?
How to add space between every 4 numbers?

Time:09-17

    <input type="text" maxlength="19" placeholder="0000 0000 0000 0000">

When user write credit card number it must add auto space between every 4 numbers. How can I do this in JavaScript?

CodePudding user response:

This one is pretty straightforward, using the "input" event with vanilla JS

const input = document.getElementById("credit-card-input");
input.addEventListener("input", () => input.value = formatNumber(input.value.replaceAll(" ", "")));

const formatNumber = (number) => number.split("").reduce((seed, next, index) => {
  if (index !== 0 && !(index % 4)) seed  = " ";
  return seed   next;
}, "");
<input id="credit-card-input" type="text" maxlength=19 placeholder="0000 0000 0000 0000">

CodePudding user response:

here is my implementation

const getMaskedValue = (value: string) => Array.from(value.replaceAll(/\D/g, '').matchAll(/(\d{0,4})(\d{0,4})(\d{0,4})(\d{0,4})/g))[0].slice(1, 5).join(' ').trim()

value should be string it will match only digit values, any other character will be removed

explanation:

  1. value.replaceAll will replace all non-digit values
  2. regex will match 4 digit groups
  3. matchAll will return regexp iterator instance
  4. array from will create array from this object
  5. we will join array with ' ' and trim for any whitespaces around
  • Related