[英]Why using .filter() together with .match() is only returning the first element matching the condition?
[英]Why is match returning the whole string as the first element in the array?
假设我有以下字符串:
'1234*321*123'
我想将每一组数字作为数组中的一个元素。
所以我用了这个:
'1234*321*123'.match(/^(\d{4})\*(\d{3})\*(\d{3})$/);
但是,当我期待的是["1234", "321", "123"]
时,返回的是["1234*321*123", "1234", "321", "123"]
["1234", "321", "123"]
。
为什么如果仅将数字组括在捕获组中,则match
将整个字符串作为数组的第一个元素返回?
零元素始终是完整匹配。 第一个元素是第一个捕获,第二个元素是第二个捕获, result.slice(1)
。如果只希望没有完全匹配的所有捕获,则可以使用result.slice(1)
。
如果您问“为什么第一个元素完全匹配?” :
match
的方式。 $0
相对于$1
, $2
...相对应。 当您使用()
进行匹配时,它会同时提供特定的组件和完整的字符串。 为了获得想要的结果,请使用以下命令:
'1234*321*123'.match(/\d+/g);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.