关于javascript:尝试拆分连字符和下划线并记住数字组产生空字符串和未定义

trying to split on hyphens and underscores and remember groups of numbers produces empty strings and undefined

本问题已经有最佳答案,请猛点这里访问。

我正在尝试创建一个单行regex数组值,该值在连字符和下划线上拆分,并在数字组(一个或多个)上拆分(并记住)。我编写了一个regex来实现这一点,但它也将空字符串和undefined插入到结果数组中。https://jsfiddle.net/vdmomiql/

1
2
3
4
5
6
var x = '232as-df98_rew_98_9fg9-dd988fff.jpg';

console.log(x.split(/(?:[-._])|(\d+)/));

//the output
//["","232","as", undefined,"df","98","", undefined,"rew", undefined,"","98","", undefined,"","9","fg","9","", undefined,"dd","988","fff", undefined,"jpg"]

我到底做错了什么?我的意思是regex似乎在逻辑上是正确的(从一个可读的角度来看是有意义的),但是空字符串和undefined是非常奇怪的

更新这更多的是关于regex的问题,然后只是从数组中删除空索引。我想说的是:这个regex有什么问题,它创建了那些空字符串和undefined


您可以通过稍微反转regex来使用match,而不是split

1
2
3
var x = '232as-df98_rew_98_9fg9-dd988fff.jpg'
console.log(x.match(/\d+|[^\d_.-]+/g))
//=> ["232","as","df","98","rew","98","9","fg","9","dd","988","fff","jpg"]

否则,您可以使用生成的数组的.filter(Boolean)来过滤undefined值:

1
2
console.log(x.split(/(?:[-._])|(\d+)/).filter(Boolean))
//=> ["232","as","df","98","rew","98","9","fg","9","dd","988","fff","jpg"]

问题是,在您的regex的有条件执行部分中,在|之后有一个组(\d+)。当该节的计算结果与拆分的字符串不匹配时,它会向数组中插入一个undefined,因为在该特定匹配中从未定义组。

要确认这一点,请注意数组中的其他所有值(具有奇数索引)要么是一个数字串,要么是undefined

空字符串出现在连字符、下划线或字符串的开头或结尾与数字字符串相邻的情况下,这部分内容至少看起来很直观。