js 搜索实现
实现 JavaScript 搜索功能
JavaScript 搜索功能可以通过多种方式实现,包括原生 JavaScript 方法、正则表达式、以及结合 DOM 操作。以下是几种常见的实现方法:
使用 includes() 方法进行简单搜索
includes() 方法可以检查字符串是否包含指定的子字符串,返回布尔值。
const text = "Hello, world!";
const searchTerm = "world";
const isFound = text.includes(searchTerm); // true
使用 indexOf() 方法进行搜索
indexOf() 方法返回子字符串在字符串中的起始位置,未找到则返回 -1。

const text = "Hello, world!";
const searchTerm = "world";
const position = text.indexOf(searchTerm); // 7
使用正则表达式进行高级搜索
正则表达式可以实现更复杂的搜索逻辑,如大小写不敏感、全局匹配等。
const text = "Hello, World!";
const searchTerm = /world/i; // i 表示大小写不敏感
const isFound = searchTerm.test(text); // true
在数组中搜索元素
可以使用 Array.prototype.includes()、Array.prototype.indexOf() 或 Array.prototype.find() 方法在数组中搜索元素。

const array = ["apple", "banana", "orange"];
const searchTerm = "banana";
const isFound = array.includes(searchTerm); // true
// 使用 find 方法搜索对象数组
const fruits = [{ name: "apple" }, { name: "banana" }];
const foundFruit = fruits.find(fruit => fruit.name === "banana"); // { name: "banana" }
结合 DOM 实现页面内容搜索
通过遍历 DOM 元素,可以搜索页面中的文本内容并高亮显示匹配项。
function searchInPage(searchTerm) {
const elements = document.querySelectorAll("p, span, div"); // 选择需要搜索的元素
elements.forEach(element => {
if (element.textContent.includes(searchTerm)) {
element.style.backgroundColor = "yellow"; // 高亮显示匹配项
}
});
}
实现实时搜索(输入框动态搜索)
通过监听输入框的输入事件,可以实现实时搜索功能。
<input type="text" id="searchInput" placeholder="Search...">
<ul id="results"></ul>
const searchInput = document.getElementById("searchInput");
const resultsContainer = document.getElementById("results");
const items = ["Apple", "Banana", "Orange"];
searchInput.addEventListener("input", (e) => {
const searchTerm = e.target.value.toLowerCase();
resultsContainer.innerHTML = "";
const filteredItems = items.filter(item =>
item.toLowerCase().includes(searchTerm)
);
filteredItems.forEach(item => {
const li = document.createElement("li");
li.textContent = item;
resultsContainer.appendChild(li);
});
});
使用第三方库实现搜索
一些第三方库(如 Fuse.js)可以提供更强大的模糊搜索功能。
// 引入 Fuse.js 后使用
const fuse = new Fuse(items, { keys: ["name"] });
const result = fuse.search("ban");
总结
JavaScript 提供了多种方式实现搜索功能,从简单的字符串匹配到复杂的 DOM 操作和第三方库集成。根据具体需求选择合适的方法即可。






