From 26cf50d96ff1f7acfde1d56a3bce1d6faf638178 Mon Sep 17 00:00:00 2001 From: Mason Hu Date: Tue, 17 Sep 2024 10:07:03 +0200 Subject: [PATCH] fix: fix highlightSubstring not being able to handle special characters for regex Signed-off-by: Mason Hu --- src/utils.test.ts | 7 +++++++ src/utils.ts | 4 +++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/utils.test.ts b/src/utils.test.ts index 7031b7ff7..6f9cbdf9f 100644 --- a/src/utils.test.ts +++ b/src/utils.test.ts @@ -21,4 +21,11 @@ describe("highlightSubString function ", () => { match: false, }); }); + + it("handles special substrings for regex matching", () => { + expect(highlightSubString("somestring\\", "\\")).toEqual({ + text: "somestring\\", + match: true, + }); + }); }); diff --git a/src/utils.ts b/src/utils.ts index cca6daaf7..0bb1e20a4 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -19,7 +19,9 @@ export const highlightSubString = ( match: false, }; } - const caseInsensitiveRegex = new RegExp(subString, "gi"); + + const escapedSubstring = subString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const caseInsensitiveRegex = new RegExp(escapedSubstring, "gi"); const newStr = str.replace( caseInsensitiveRegex, (match) => `${match}`,