You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中用正则表达式过滤含额外内容的JSON交易数据

解决方案:结合正则表达式过滤交易数据

直接用Array.filter()结合正则的test()方法就能实现需求,以下是具体实现:

核心代码示例

假设你的交易数据数组为transactions,可以这样写:

// 过滤出type为transfer且comment包含"Storefront Restock"(不区分大小写)的记录
const filteredTransactions = transactions.filter(transaction => {
  return transaction.type === 'transfer' && /Storefront Restock/i.test(transaction.comment);
});

关键细节说明

  • 正则表达式/Storefront Restock/i中的i标志表示不区分大小写,能匹配诸如"storefront restock"、"StoreFront Restock"这类变体;如果不需要忽略大小写,去掉i即可
  • RegExp.test()方法会返回布尔值,刚好满足filter()回调函数需要返回判断结果的要求,只要comment包含目标字符串就会返回true
  • 如果你需要保留全局匹配标志g,注意每次调用test()前要重置正则的lastIndex属性,避免因累积索引导致的错误匹配:
const restockRegex = /Storefront Restock/gi;
const filteredTransactions = transactions.filter(transaction => {
  restockRegex.lastIndex = 0; // 重置索引
  return transaction.type === 'transfer' && restockRegex.test(transaction.comment);
});

效果验证

不管comment字段带有额外内容(比如"Storefront Restock - 补货批次A"、"【Storefront Restock】紧急补货"),只要包含目标字符串片段,都会被正确筛选出来。

内容的提问来源于stack exchange,提问作者Manvaril

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:50:54