From 5a23a4d217da2904841e5a783ff8fe00810255e8 Mon Sep 17 00:00:00 2001 From: Hk-Gosuto Date: Tue, 19 Nov 2024 02:32:56 +0000 Subject: [PATCH] fix: search special character error --- app/components/search-bar.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/components/search-bar.tsx b/app/components/search-bar.tsx index 91f4b0f7a..a73f2d59d 100644 --- a/app/components/search-bar.tsx +++ b/app/components/search-bar.tsx @@ -37,15 +37,19 @@ export interface SearchInputRef { inputElement: HTMLInputElement | null; } +function escapeRegExp(search: string) { + return search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + function highlightAndShorten(str: string, search: string) { const index = str.toLowerCase().indexOf(search.toLowerCase()); const head = Math.max(0, index - 10); const tail = Math.min(str.length, index + search.length + 40); // Remove code block syntax let result = str.slice(head, tail); - + const safeSearch = escapeRegExp(search); // Use ** to highlight the search result - result = result.replace(new RegExp(`(${search})`), "**$1**"); + result = result.replace(new RegExp(`(${safeSearch})`), "**$1**"); if (head > 0) { result = "..." + result;