Fuse.js 是一个轻量级的 JavaScript 库,专注于实现模糊搜索和文本匹配功能。它采用近似字符串匹配算法,能够在大型数据集中快速找到匹配项,同时还支持高级的搜索选项和自定义配置。 Fuse.js | Fuse.js (fusejs.io)
安装
npm install fuse.js
# 或者
yarn add fuse.js
基本用法
// 导入 Fuse.js
import Fuse from 'fuse.js'
# 或者
import Fuse from 'fuse.js/dist/fuse.min.js'
// 示例数据 - 一个包含多个对象的数组
const books = [
{ title: 'JavaScript: The Good Parts' },
{ title: 'Eloquent JavaScript' },
{ title: 'JavaScript: The Definitive Guide' },
{ title: 'Learning JavaScript Design Patterns' },
{ title: 'You Don’t Know JS' },
];
// 创建 Fuse.js 实例并配置搜索选项
const options = {
keys: ['title'], // 搜索的键,这里只搜索 'title' 属性
};
const fuse = new Fuse(books, options);
// 执行模糊搜索
const result = fuse.search('JavaScript');
// 输出搜索结果
console.log(result);
自定义搜索选项
const options = {
keys: ['title', 'author'], // 多个搜索键
threshold: 0.6, // 阈值控制匹配的敏感度
shouldSort: true, // 是否对结果进行排序
location: 0, // 匹配的位置,0 表示开头匹配
distance: 100, // 搜索的最大距离
minMatchCharLength: 2, // 最小匹配字符长度
};
{
shouldSort: true,
threshold: 0.1,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [{
name: 'title',
weight: 0.7
}, {
name: 'path',
weight: 0.3
}]
}
自定义搜索函数
const customSearchFunction = (pattern, options) => {
// 自定义搜索逻辑
// 返回匹配项的数组
};
const fuse = new Fuse(data, { customSearch: customSearchFunction });