From 7593168032cf379d62b150b3264a309ebce3e7c3 Mon Sep 17 00:00:00 2001 From: Jimmy Cai Date: Wed, 29 Dec 2021 13:56:21 +0000 Subject: [PATCH] Use | operator to concatenate keywords Idea from https://github.com/CaiJimmy/hugo-theme-stack/pull/436 --- assets/jsconfig.json | 2 ++ assets/ts/search.tsx | 37 ++++++++++++++++++------------------- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/assets/jsconfig.json b/assets/jsconfig.json index 9321136..040177a 100644 --- a/assets/jsconfig.json +++ b/assets/jsconfig.json @@ -6,5 +6,7 @@ "*" ] }, + "lib": ["es2020", "dom"], + "jsx": "preserve" } } \ No newline at end of file diff --git a/assets/ts/search.tsx b/assets/ts/search.tsx index 1dec462..1960dbc 100644 --- a/assets/ts/search.tsx +++ b/assets/ts/search.tsx @@ -104,6 +104,11 @@ class Search { const rawData = await this.getData(); 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) { let titleMatches: match[] = [], contentMatches: match[] = []; @@ -114,26 +119,20 @@ class Search { matchCount: 0 } - for (const keyword of keywords) { - if (keyword === '') continue; + const contentMatchAll = item.content.matchAll(regex); + for (const match of Array.from(contentMatchAll)) { + contentMatches.push({ + start: match.index, + end: match.index + match[0].length + }); + } - const regex = new RegExp(escapeRegExp(keyword), 'gi'); - - const contentMatchAll = item.content.matchAll(regex); - for (const match of Array.from(contentMatchAll)) { - contentMatches.push({ - start: match.index, - end: match.index + match[0].length - }); - } - - const titleMatchAll = item.title.matchAll(regex); - for (const match of Array.from(titleMatchAll)) { - titleMatches.push({ - start: match.index, - end: match.index + match[0].length - }); - } + const titleMatchAll = item.title.matchAll(regex); + for (const match of Array.from(titleMatchAll)) { + titleMatches.push({ + start: match.index, + end: match.index + match[0].length + }); } if (titleMatches.length > 0) result.title = Search.processMatches(result.title, titleMatches).join('');