我不明白为什么 undefined
出现在结果中。我用了一个问号(\d+)?
,它matches the previous element zero or one time :
// I want to match two cases with one regexp:
// "GBP 5 per hour" and "GBP 5 per 10 hours"
//
"GBP 5 per hour".match(/([a-z]{3}) (\d+(?:\.\d+)?) per\s?(\d+)?\s?(hours?|days?|minutes?)/im)
["GBP 5 per hour", "GBP", "5", undefined, "hour"] // actual result
["GBP 5 per hour", "GBP", "5", "hour"] // the result I'd like to get
如何摆脱那个undefined
?
最佳答案
结果将是匹配的数据(文本),如果你说你想匹配零或一,它匹配零则没有数据返回,undefined 是结果。
我推测保留匹配的设计原因是因为它使索引保持一致,因此您仍然可以按预期访问它们。这样,您就可以通过检查 undefined
来有效地测试“是否匹配”。
如果你想从数组中删除它,那么你可以使用 filter
函数,例如:
arr = arr.filter(function(e){return e});
关于javascript - 如何摆脱正则表达式结果中的 "undefined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21257016/