javascript - 使用正则表达式过滤数组列表
问题描述
我正在尝试过滤这个
Alert me when this account’s current balance goes above $1.
从这里的列表中:
alertTypes = [
'Alert me when this account’s available balance goes below $1.',
'Alert me when this account’s current balance goes below $1.',
'Alert me when this account’s available balance goes above $1.',
'Alert me when this account’s current balance goes above $1.']
使用这个异步函数
const alertRegEx = "/.*current balance.*above.*/"
const alert = alertTypes.filter(alert => alert.match(alertRegEx))
但是我在警报变量中获得了整个列表。我在这里有什么错误?
解决方案
首先,不要async
在这种情况下使用它,因为match
它不是异步函数(但即使它是你也无法在 a 中使用它filter
)。然后你需要使用文字正则表达式,而不是字符串。
一个次要的,非必需的更改是您可以跳过初始和最终.*
const alertTypes = [
'Alert me when this account’s available balance goes below $1.',
'Alert me when this account’s current balance goes below $1.',
'Alert me when this account’s available balance goes above $1.',
'Alert me when this account’s current balance goes above $1.']
const alertRegEx = /current balance.*above/;
const alerts = alertTypes.filter( alert => alert.match(alertRegEx))
console.log(alerts);