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"]
That's because the regex is keeping state. Either:
Create it each time, or
Set
lastIndex
to 0 before using itHere's #1:
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:
Obviously, both can be shortened if you can use ES2015+ arrow functions and such...