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

Angular 5自定义筛选搜索需求:开头匹配、指定字段搜索

实现前缀匹配的筛选功能

首先先看你提供的原始数据:

data : [ 
  { id :1, name : "client A", industry: "Industry 1", img:"https://abc" }, 
  { id :2, name : "client Ab", industry: "Industry 2", img:"https://abc" }, 
  { id :3, name : "client megha", industry: "Industry 5", img:"https://abc" }, 
  { id :4, name : "shubham", industry: "Industry 1", img:"https://abc" }, 
  { id :4, name : "rick", industry: "Industry 1", img:"https://abc" } 
]

你的需求梳理

你需要实现的筛选逻辑是:

  • 输入框为空时,显示所有数据
  • 输入关键词时,只保留名称或行业以关键词开头的条目(比如输入"c"时,"rick"会被过滤掉,因为它的name和industry都不以"c"开头;输入"m"时没有结果,因为没有条目满足前缀匹配)
  • 不使用strict模式,仅基于name和industry字段筛选,忽略img字段

解决方案代码

我给你写一个自定义的筛选函数,用JavaScript实现的话,核心是用startsWith方法做前缀匹配,同时处理大小写问题(这样用户输入大写小写都能匹配):

function filterClients(data, searchKeyword) {
  // 搜索词为空时直接返回全部数据
  if (!searchKeyword.trim()) {
    return [...data];
  }
  
  // 统一转成小写,避免大小写敏感
  const lowerKeyword = searchKeyword.toLowerCase();
  
  return data.filter(item => {
    // 检查name是否以关键词开头
    const nameMatches = item.name.toLowerCase().startsWith(lowerKeyword);
    // 检查industry是否以关键词开头
    const industryMatches = item.industry.toLowerCase().startsWith(lowerKeyword);
    
    // 只要其中一个字段符合前缀匹配就保留
    return nameMatches || industryMatches;
  });
}

// 测试示例
const clientData = [ 
  { id :1, name : "client A", industry: "Industry 1", img:"https://abc" }, 
  { id :2, name : "client Ab", industry: "Industry 2", img:"https://abc" }, 
  { id :3, name : "client megha", industry: "Industry 5", img:"https://abc" }, 
  { id :4, name : "shubham", industry: "Industry 1", img:"https://abc" }, 
  { id :4, name : "rick", industry: "Industry 1", img:"https://abc" } 
];

// 输入"c"的结果:只有前3条(name以c开头)会被保留,rick被过滤
console.log(filterClients(clientData, "c"));

// 输入"m"的结果:空数组,因为没有条目满足前缀匹配
console.log(filterClients(clientData, "m"));

逻辑说明

  1. 先判断搜索词是否为空,为空则直接返回所有数据,满足“无值时显示全部”的需求
  2. 把搜索词和要匹配的字段都转成小写,这样用户输入"C"或者"c"都能匹配到"client A",提升用户体验
  3. 用startsWith方法替代默认的包含匹配,确保只有字段开头和关键词一致的条目才会被保留,完美解决你说的"rick"在输入"c"时被错误显示的问题
  4. 只针对name和industry字段做判断,完全忽略img字段,符合你的要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:28:13