js搜索实现
JavaScript 搜索实现方法
基本字符串搜索
使用 includes() 方法检查字符串是否包含子串:
const str = "Hello World";
const result = str.includes("World"); // true
使用 indexOf() 获取子串位置:
const position = str.indexOf("World"); // 6
正则表达式搜索
使用 test() 方法进行模式匹配:
const regex = /world/i;
const isMatch = regex.test("Hello World"); // true
使用 match() 提取匹配结果:
const matches = "2023-04-01".match(/\d+/g); // ["2023", "04", "01"]
数组搜索
使用 find() 查找符合条件的第一项:
const users = [{id:1, name:"Alice"}, {id:2, name:"Bob"}];
const user = users.find(u => u.id === 2); // {id:2, name:"Bob"}
使用 filter() 筛选所有匹配项:
const filteredUsers = users.filter(u => u.name.includes("A")); // [{id:1, name:"Alice"}]
模糊搜索实现
结合字符串处理和正则表达式实现模糊匹配:
function fuzzySearch(text, query) {
const pattern = query.split("").join(".*");
return new RegExp(pattern, "i").test(text);
}
fuzzySearch("Electronics", "eltr"); // true
搜索算法优化
对于大型数据集,考虑预先建立索引:
const searchIndex = {};
data.forEach(item => {
const keywords = item.name.toLowerCase().split(" ");
keywords.forEach(key => {
searchIndex[key] = searchIndex[key] || [];
searchIndex[key].push(item);
});
});
前端实时搜索
监听输入事件实现即时搜索:
const searchInput = document.getElementById("search");
searchInput.addEventListener("input", (e) => {
const results = data.filter(item =>
item.name.toLowerCase().includes(e.target.value.toLowerCase())
);
renderResults(results);
});
高级搜索库
考虑使用专业搜索库如Lunr.js:

const idx = lunr(function() {
this.ref("id");
this.field("title");
this.field("body");
documents.forEach(doc => this.add(doc));
});
const results = idx.search("query");






