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

如何在JavaScript数组中查找与含通配符的字符串匹配的元素

匹配实现方案

你可以把模式里的下划线作为单字符占位符,替换为正则的单字符通配符.,再构造带首尾限定的正则规则,用数组filter方法筛选即可,示例代码如下:

const fruit = ["apple", "banana", "strawberry", "grape"];
const word = "a__ple";

// 下划线替换为单字符匹配规则,加^和$限定完全匹配整个单词
const matchReg = new RegExp(`^${word.replace(/_/g, '.')}$`);
const result = fruit.filter(item => matchReg.test(item));

console.log(result); // 输出符合匹配规则的结果:["apple"]

注意事项

  • 如果模式中包含.、*、+这类正则特殊字符,需要先对特殊字符做转义处理,避免匹配逻辑异常,转义版代码如下:
const fruit = ["apple", "banana", "strawberry", "grape"];
const word = "a__ple";
// 先转义所有正则特殊字符,再替换下划线为通配符
const escapedWord = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/_/g, '.');
const matchReg = new RegExp(`^${escapedWord}$`);
const result = fruit.filter(item => matchReg.test(item));
  • 低版本JS环境如果不支持replaceAll,使用全局匹配的replace(/_/g, '.')即可实现相同效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 09:18:03