Skip to content

Commit

Permalink
fix: fix highlightSubstring not being able to handle special characte…
Browse files Browse the repository at this point in the history
…rs for regex

Signed-off-by: Mason Hu <[email protected]>
  • Loading branch information
mas-who committed Sep 17, 2024
1 parent 26793e5 commit 26cf50d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,11 @@ describe("highlightSubString function ", () => {
match: false,
});
});

it("handles special substrings for regex matching", () => {
expect(highlightSubString("somestring\\", "\\")).toEqual({
text: "somestring<strong>\\</strong>",
match: true,
});
});
});
4 changes: 3 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => `<strong>${match}</strong>`,
Expand Down

0 comments on commit 26cf50d

Please sign in to comment.