From b848cfd921e649f03830cc91f3bec891f4c40b93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Malak?= Date: Fri, 12 Nov 2021 14:02:19 +0100 Subject: [PATCH] Added function to escape regex characters --- client/src/components/Home/Home.tsx | 11 +++++++++-- client/src/utility/escapeRegex.ts | 6 ++++++ client/src/utility/index.ts | 1 + 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 client/src/utility/escapeRegex.ts diff --git a/client/src/components/Home/Home.tsx b/client/src/components/Home/Home.tsx index 1b96b66..43b2373 100644 --- a/client/src/components/Home/Home.tsx +++ b/client/src/components/Home/Home.tsx @@ -22,6 +22,9 @@ import { BookmarkGrid } from '../Bookmarks/BookmarkGrid/BookmarkGrid'; import { SearchBar } from '../SearchBar/SearchBar'; import { Header } from './Header/Header'; +// Utils +import { escapeRegex } from '../../utility'; + export const Home = (): JSX.Element => { const { apps: { apps, loading: appsLoading }, @@ -60,7 +63,9 @@ export const Home = (): JSX.Element => { if (localSearch) { // Search through apps setAppSearchResult([ - ...apps.filter(({ name }) => new RegExp(localSearch, 'i').test(name)), + ...apps.filter(({ name }) => + new RegExp(escapeRegex(localSearch), 'i').test(name) + ), ]); // Search through bookmarks @@ -70,7 +75,9 @@ export const Home = (): JSX.Element => { category.bookmarks = categories .map(({ bookmarks }) => bookmarks) .flat() - .filter(({ name }) => new RegExp(localSearch, 'i').test(name)); + .filter(({ name }) => + new RegExp(escapeRegex(localSearch), 'i').test(name) + ); setBookmarkSearchResult([category]); } else { diff --git a/client/src/utility/escapeRegex.ts b/client/src/utility/escapeRegex.ts new file mode 100644 index 0000000..3fc002a --- /dev/null +++ b/client/src/utility/escapeRegex.ts @@ -0,0 +1,6 @@ +/** + * https://stackoverflow.com/a/30851002/16957052 + */ +export const escapeRegex = (exp: string) => { + return exp.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&'); +}; diff --git a/client/src/utility/index.ts b/client/src/utility/index.ts index 9ca9bba..7358da4 100644 --- a/client/src/utility/index.ts +++ b/client/src/utility/index.ts @@ -11,3 +11,4 @@ export * from './validators'; export * from './parseTime'; export * from './decodeToken'; export * from './applyAuth'; +export * from './escapeRegex';