From 59a314dfca16b2b5d5f21ff43b940b06ae6b7569 Mon Sep 17 00:00:00 2001 From: Colin Claverie Date: Thu, 21 Dec 2023 10:11:36 +0000 Subject: [PATCH] fix: escape regex special characters --- src/index.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 9dbdb72..df73709 100644 --- a/src/index.ts +++ b/src/index.ts @@ -52,6 +52,10 @@ const parseMatchedTextNode = (regexp: RegExp, node: ChildNode, style?: string) = } const highlightElements = (el: HTMLElement, value: Array, style?: string) => { + + // escape regex special characters (similar to preg_quote in PHP) + value = value.map(val => val.replace(/[-[\]{}()*+?.,\\^$|#\s]/ig, "\\$&")) + const regexp = new RegExp(value.join("|"), "gi"); if (!el.textContent?.match(regexp)) { @@ -90,4 +94,4 @@ const unhighlightElements = (el: HTMLElement) => { queue = queue.concat(Array.from(curr.childNodes)) } } -} \ No newline at end of file +}