我如何让它在includes((或其他方式中显示准确性。。。例如,我是这样做的。
array.filter(item => {
if(item?.about?.toLowerCase()?.includes(
("4")) && item?.about?.toLowerCase()?.includes(
("years")
)
但在文本本身中,它被写为,例如,";我们已经存在了40年">
它能识别40中的数字4,然后对其进行过滤。
我们能做什么?
您可以使用Regex将多个测试作为单个模式包括在内:
/(^4|[^d]+4)[^d]+years.*/i
解释:
- (^4|[^\d]+4(:字符串以4开头,或者前面有一个非数字字符
- [^\d]+:后面至少跟一个非数字字符
- years:后面跟单词years
- .*:表示后面可以有任何字符,也可以在末尾
- /i: 意味着它将不敏感地检查大小写。所以您不必执行
.toLowerCase()
const data = [ "We have existed for 40 years", "We have existed for 4 years", "We have existed for 44 years", "4 years at start", "4 is a random number in years" ] const output = data.filter((str) => { const regex = /(^4|[^d]+4)[^d]+years.*/i; return regex.test(str) }); console.log(output)