javascriptregexiban

How to add whitespace for array of IBAN properly


I want to ask a question about regex.

I have an array of IBAN.

eg ["DE46700202700663820656", "DE07860700240455474700"]

I want to add whitespace between each 4 characters.

eg "DE46 7002 0270 0663 8206 56"

Currently I use this regex.

String(this.props.invoiceData.iban).replace(/(.{4})/g, '$1 ').split(',')

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

eg ["DE46 7002 0270 0663 8206 56", "D E078 6070 0240 4554 7470 0"]

What should I do to show two IBAN with proper whitespace as below?

eg ["DE46 7002 0270 0663 8206 56", "DE07 8607 0024 0455 4747 00"]


Solution

  • 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);

    Unless you're using an ancient JavaScript engine that has an issue with not recreating literal regular expressions each time (we're talking Firefox 3.0x or thereabouts), that should be fine.

    Here's #2:

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

    Obviously, both can be shortened if you can use ES2015+ arrow functions and such...