Skip to content

Commit

Permalink
fix: search special character error
Browse files Browse the repository at this point in the history
  • Loading branch information
Hk-Gosuto committed Nov 19, 2024
1 parent f43c5c0 commit 5a23a4d
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions app/components/search-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 5a23a4d

Please sign in to comment.