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

As stated above, the caveat is that you can't go back and edit previous characters. If you want to fix this, you would need to retrieve the caret's current position by initially accessing the selectionEnd property and then setting the caret's position after the regex formatting has been applied.

document.getElementById('iban').addEventListener('input', function (e) {
  var target = e.target, position = target.selectionEnd, length = target.value.length;
  
  target.value = target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
  target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
});
<label for="iban">iban</label>
<input id="iban" type="text" name="iban" />

You will notice that there is a slight issue when the character after the caret is a space (because the space wasn't accounted for when initially retrieving the caret's position to begin with). To fix this, the position is manually incremented if the succeeding character is a space (assuming a space was actually added - which is determined by comparing the length before and after replacing the characters).


Using plain-JavaScript, I'd suggest:

function space(el, after) {
    // defaults to a space after 4 characters:
    after = after || 4;

    /* removes all characters in the value that aren't a number,
       or in the range from A to Z (uppercase): */
    var v = el.value.replace(/[^\dA-Z]/g, ''),
    /* creating the regular expression, to allow for the 'after' variable
       to be used/changed: */
        reg = new RegExp(".{" + after + "}","g")
    el.value = v.replace(reg, function (a, b, c) {
        return a + ' ';
    });
}

var el = document.getElementById('iban');
el.addEventListener('keyup', function () {
    space(this, 4);
});

JS Fiddle demo.

Somewhat belatedly, my rewrite of the above to handle strings, rather than DOM nodes:

function space(str, after) {
    if (!str) {
        return false;
    }
    after = after || 4;
    var v = str.replace(/[^\dA-Z]/g, ''),
        reg = new RegExp(".{" + after + "}", "g");
    return v.replace(reg, function (a) {
        return a + ' ';
    });
}

var el = document.getElementById('iban');
el.addEventListener('keyup', function () {
    this.value = space(this.value, 4);
});

JS Fiddle demo.

References:

  • addEventListener().
  • JavaScript regular expressions.

The code from Josh Crozie is really nice, but not complete.

Two issues with it;

  • If the caret is not at the end but e.g. at the before last position and the user starts typing, sometimes the caret doesn't stay at the before last position
  • Another issue is with Android 7+ devices. Those devices update the caret position slightly later, that means it needs a setTimeout() before reading the caret location

The code below is based on the code of Josh Crozie, now with the two issues mentioned above fixed and a little more verbose for readability purpose:

var isAndroid = navigator.userAgent.indexOf("ndroid") > -1;
var element = document.getElementById('iban');

element.addEventListener('input', function () {
    if (isAndroid) {
        // For android 7+ the update of the cursor location is a little bit behind, hence the little delay.
        setTimeout(reformatInputField);
        return;
    }
    reformatInputField();
});

function reformatInputField() {
    function format(value) {
        return value.replace(/[^\dA-Z]/gi, '')
            .toUpperCase()
            .replace(/(.{4})/g, '$1 ')
            .trim();
    }
    function countSpaces(text) {
        var spaces = text.match(/(\s+)/g);
        return spaces ? spaces.length : 0;
    }

    var position = element.selectionEnd;
    var previousValue = element.value;
    element.value = format(element.value);

    if (position !== element.value.length) {
        var beforeCaret = previousValue.substr(0, position);
        var countPrevious = countSpaces(beforeCaret);
        var countCurrent = countSpaces(format(beforeCaret));
        element.selectionEnd = position + (countCurrent - countPrevious);
    }
}
<label for="iban">iban</label>
<input id="iban" type="text" name="iban" size="35" />

You have to capture each group of 4 digits and then put a space between each group.

  $('input').blur(function () {
  //Replace each group 4 digits  with a group plus a space
        var reformat = this.value.replace(/(\d{4})/g, function(match){
        return match + " ";
        });
        this.value = reformat;
    })

And this one updates the element while typing

 //Keys pressed 0 times
var downed = 0; 
$('#test').keydown(function (g) {
    if(g.code.match("^Digit")){
        downed++;
      console.log(g)
    }

    if(downed == 1){
        var reformat = this.value.replace(/(\d{4}\s*)/g, function(match){
            //Strip spaces
            if(match.match(/\s/)){return match;}
            return match + " ";
    });
    console.log(reformat);
    this.value = reformat; 
    //Start recount
        downed = 0;
    }
});

Check out the fiddle


I wrote a simple function extending David's function to handle the last space. Also you can specify the separator.

function spacify(str, after, c) {
    if (!str) {
        return false;
    }
    after = after || 4;
    c = c || " ";
    var v = str.replace(/[^\dA-Z]/g, ''),
        reg = new RegExp(".{" + after + "}", "g");
    return v.replace(reg, function (a) {
        return a + c;
    }).replace(/[^0-9]+$/, "");
}
console.log(spacify("123123123131",4," "))
console.log(spacify("12312312313",4,"-"))