Skip to content

Commit

Permalink
fix: escape regex special characters
Browse files Browse the repository at this point in the history
  • Loading branch information
coclav authored and d8vjork committed Dec 21, 2023
1 parent 1498676 commit 59a314d
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ const parseMatchedTextNode = (regexp: RegExp, node: ChildNode, style?: string) =
}

const highlightElements = (el: HTMLElement, value: Array<string>, 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)) {
Expand Down Expand Up @@ -90,4 +94,4 @@ const unhighlightElements = (el: HTMLElement) => {
queue = queue.concat(Array.from(curr.childNodes))
}
}
}
}

0 comments on commit 59a314d

Please sign in to comment.