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

如何在JS中实现不区分大小写的数组部分字符串模糊匹配功能

JS模糊匹配汽车名称功能实现

核心实现逻辑

  • 先校验输入关键词长度,不足3个字符直接返回空结果
  • 将关键词和数组中所有字符串统一转为小写,实现不区分大小写的匹配效果
  • 通过字符串匹配方法判断子串是否存在

完整代码实现

const carsName = [
    "Landstalker",
    "Bravura",
    "Buffalo",
    "Linerunner",
    "Perrenial",
    "Sentinel",
    "Dumper",
    "Firetruck",
    "Trashmaster",
    "Stretch",
    "Manana",
    "Infernus"
];

/**
 * 汽车名称模糊搜索函数
 * @param {string} keyword 搜索关键词
 * @returns {Array} 匹配到的汽车名称数组
 */
function searchCars(keyword) {
    // 校验关键词最小长度要求
    if (keyword.length < 3) return [];
    // 统一转为小写消除大小写差异
    const formattedKeyword = keyword.toLowerCase();
    // 遍历过滤出匹配的元素
    return carsName.filter(carItem => {
        return carItem.toLowerCase().includes(formattedKeyword);
    });
}

使用示例

// 测试用例
console.log(searchCars('buf')); // 输出:['Buffalo']
console.log(searchCars('Buff')); // 输出:['Buffalo']
console.log(searchCars('fire')); // 输出:['Firetruck']
console.log(searchCars('man')); // 输出:['Manana']

可选调整

如果需要限制仅匹配字符串开头的片段(比如输入buf只能匹配开头为buf的Buffalo,无法匹配中间包含buf的其他字符串),可以将代码中的includes方法替换为startsWith即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:39:04