简体   繁体   English

如何正确为IBAN数组添加空格

[英]How to add whitespace for array of IBAN properly

I want to ask a question about regex. 我想问一个关于正则表达式的问题。

I have an array of IBAN. 我有一组IBAN。

eg ["DE46700202700663820656", "DE07860700240455474700"] 例如["DE46700202700663820656", "DE07860700240455474700"]

I want to add whitespace between each 4 characters. 我想在每个4个字符之间添加空格。

eg "DE46 7002 0270 0663 8206 56" 例如"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. 它可以添加空格,但是正则表达式不会针对第二个IBAN重新启动,并且第二个IBAN被销毁。

eg ["DE46 7002 0270 0663 8206 56", "D E078 6070 0240 4554 7470 0"] 例如["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? 如何显示两个具有适当空格的IBAN,如下所示?

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

It could add whitespace but regex does not restart for a second IBAN and second IBAN is destroyed. 它可以添加空格,但是正则表达式不会针对第二个IBAN重新启动,并且第二个IBAN被销毁。

That's because the regex is keeping state. 这是因为正则表达式保持状态。 Either: 要么:

  1. Create it each time, or 每次创建它,或者

  2. Set lastIndex to 0 before using it 在使用前将lastIndex设置为0

Here's #1: 这是#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. 除非您使用的是古老的 JavaScript引擎,而这个引擎的问题是每次都不重新创建文字正则表达式(我们说的是Firefox 3.0x或更高版本),否则应该没问题。

Here's #2: 这里是#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... 显然,如果可以使用ES2015 +箭头功能,则两者都可以缩短。

You can try like this using .map() : 您可以使用.map()这样尝试:

 var a = ["DE46700202700663820656", "DE07860700240455474700"]; var b = a.map(i => i.replace(/(.{4})/g, '$1 ')); console.log(b) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM