1

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

Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
sslswftra
  • 33
  • 3
  • I believe the term you're looking for is an "input mask". – David Sep 16 '22 at 12:50
  • you can check this library: https://imask.js.org/ – Aykhan Huseyn Sep 16 '22 at 12:53
  • Does this answer your question? [Formatting input value using javascript as the user types a value into the input field](https://stackoverflow.com/questions/66529607/formatting-input-value-using-javascript-as-the-user-types-a-value-into-the-input) – evolutionxbox Sep 16 '22 at 12:54
  • 1
    Does this answer your question? [What is the correct input type for credit card numbers?](https://stackoverflow.com/questions/48534229/what-is-the-correct-input-type-for-credit-card-numbers) – Michael M. Sep 16 '22 at 12:55
  • Welcome to Stack Overflow. Please take the [tour] and read [ask]. We expect a certain amount of research to be done before asking (see [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/215552)). – Heretic Monkey Sep 16 '22 at 12:55
  • have a look at https://bbbootstrap.com/snippets/credit-card-checkout-formatted-input-51353295 – JoSSte Sep 16 '22 at 12:56

2 Answers2

3

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">
Thomas Zimmermann
  • 1,485
  • 8
  • 18
1

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
Aykhan Huseyn
  • 94
  • 1
  • 7