Search code examples
javascripthtmlhtml-input

How to add space between every 4 numbers?


<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?


Solution

  • 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">