Use | operator to concatenate keywords

Idea from https://github.com/CaiJimmy/hugo-theme-stack/pull/436
This commit is contained in:
Jimmy Cai 2021-12-29 13:56:21 +00:00 committed by GitHub
parent d55e4f5e2d
commit 7593168032
2 changed files with 20 additions and 19 deletions

View File

@ -6,5 +6,7 @@
"*" "*"
] ]
}, },
"lib": ["es2020", "dom"],
"jsx": "preserve"
} }
} }

View File

@ -104,6 +104,11 @@ class Search {
const rawData = await this.getData(); const rawData = await this.getData();
let results: pageData[] = []; let results: pageData[] = [];
const regex = new RegExp(keywords.filter((v, index, arr) => {
arr[index] = escapeRegExp(v);
return v !== '';
}).join('|'), 'gi');
for (const item of rawData) { for (const item of rawData) {
let titleMatches: match[] = [], let titleMatches: match[] = [],
contentMatches: match[] = []; contentMatches: match[] = [];
@ -114,11 +119,6 @@ class Search {
matchCount: 0 matchCount: 0
} }
for (const keyword of keywords) {
if (keyword === '') continue;
const regex = new RegExp(escapeRegExp(keyword), 'gi');
const contentMatchAll = item.content.matchAll(regex); const contentMatchAll = item.content.matchAll(regex);
for (const match of Array.from(contentMatchAll)) { for (const match of Array.from(contentMatchAll)) {
contentMatches.push({ contentMatches.push({
@ -134,7 +134,6 @@ class Search {
end: match.index + match[0].length end: match.index + match[0].length
}); });
} }
}
if (titleMatches.length > 0) result.title = Search.processMatches(result.title, titleMatches).join(''); if (titleMatches.length > 0) result.title = Search.processMatches(result.title, titleMatches).join('');
if (contentMatches.length > 0) result.preview = Search.processMatches(result.content, contentMatches).join(''); if (contentMatches.length > 0) result.preview = Search.processMatches(result.content, contentMatches).join('');