How to Insert Space Every 4 Characters for Iban Registering

How to add whitespace for array of IBAN properly

It could add whitespace but regex does not restart for a second IBAN and second IBAN is destroyed.

That's because the regex is keeping state. Either:

  1. Create it each time, or

  2. Set lastIndex to 0 before using it

Here's #1:

var ibans = ["DE46700202700663820656", "DE07860700240455474700"];ibans = ibans.map(function(iban) {  return iban.replace(/(.{4})/g, '$1 ');});console.log(ibans);

How to insert space every 4 characters for IBAN registering?

The existing answers are relatively long, and they look like over-kill. Plus they don't work completely (for instance, one issue is that you can't edit previous characters).

For those interested, according to Wikipedia:

Permitted IBAN characters are the digits 0 to 9 and the 26 upper-case Latin alphabetic characters A to Z.

Here is a relatively short version that is similar to the existing answers:

document.getElementById('iban').addEventListener('input', function (e) {  e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();});
<label for="iban">iban</label><input id="iban" type="text" name="iban" />

Plain Javascript way to add a space on the fly after every 5th digit in input field

Here is a relatively short approach:

Just add an event listener for the input event (or keyup/keydown), and then use some regex.

In the example directly below, all whitespace is initially removed using .replace(/\s/g, ''), and then .replace(/(\d{5})/g, '$1 ') essentially adds a space after every 5th character.

The reason all the whitespace is removed is so that there is always a space between every 5th character (even if you go back and edit previous characters).