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

如何在JavaScript中实现数组模糊过滤及匹配字符高亮功能

非连续模糊搜索+匹配字符高亮实现方案

现有代码问题

  • 输入值的获取写在事件监听外部,只会在页面初始化时读取一次,后续用户输入不会更新取值,永远使用初始空值
  • 用includes判断匹配,要求输入的字符必须连续相邻,不符合非连续匹配的需求

核心实现逻辑

  1. 非连续匹配:遍历输入的每个字符,按顺序在城市名中查找对应字符,只要所有输入字符都能按顺序找到(不需要相邻),就判定为匹配
  2. 字符高亮:渲染匹配到的城市名时,将命中的字符用黄色背景的行内元素包裹

完整可运行代码

<!-- 页面结构 -->
<input type="text" placeholder="输入搜索城市">
<div id="result"></div>
const cities = ['Berlin', 'Bucharest', 'Paris', 'Munich', 'Amsterdam', 'Milan'];
const inputDom = document.querySelector("input");
const resultDom = document.querySelector("#result");

// 绑定输入监听事件
inputDom.addEventListener('input', search);

function search() {
  // 每次输入都读取最新的输入值,统一转小写去空格
  const input = inputDom.value.toLowerCase().trim();
  // 输入为空时清空结果直接返回
  if (!input) {
    resultDom.innerHTML = '';
    return;
  }
  
  // 第一步:过滤符合非连续匹配规则的城市
  const filteredCities = cities.filter(city => {
    const lowerCity = city.toLowerCase();
    let inputIndex = 0;
    for (const char of lowerCity) {
      if (char === input[inputIndex]) {
        inputIndex++;
        // 所有输入字符都已按顺序匹配到,直接判定为符合条件
        if (inputIndex === input.length) return true;
      }
    }
    // 遍历完城市名还有输入字符没匹配到,判定为不符合
    return inputIndex === input.length;
  });

  // 第二步:给匹配到的字符加高亮效果,渲染到页面
  resultDom.innerHTML = filteredCities.map(city => {
    const lowerCity = city.toLowerCase();
    let inputIndex = 0;
    let highlightedStr = '';
    for (let i = 0; i < city.length; i++) {
      if (inputIndex < input.length && lowerCity[i] === input[inputIndex]) {
        highlightedStr += `<span style="background: yellow;">${city[i]}</span>`;
        inputIndex++;
      } else {
        highlightedStr += city[i];
      }
    }
    return `<div>${highlightedStr}</div>`;
  }).join('');
}

效果验证

  • 输入m时,返回Munich、Amsterdam、Milan,所有命中的m字符都会标黄
  • 输入ma时,返回Amsterdam、Milan,对应命中的m和a字符都会标黄

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:45:03