jeudi 1 avril 2021

Regex breaking with some wildcard characters [duplicate]

I am currently working on a search feature where I would like to use some text highlighter approach whenever the user types in a keyword. Here's the code that I have come up with for the same:

const regex = new RegExp(`(${highlight})`, 'i'); // highlight here would be the entered keyword
const parts = searchLabel.split(regex); // splitting the result for proper highlighting

It works mostly well, but starts breaking when user enters * or ( or ).

Here's the error with (:

Highlighter.js:29 Uncaught SyntaxError: Invalid regular expression: /())/: Unmatched ')'

or with *

Uncaught SyntaxError: Invalid regular expression: /(*)/: Nothing to repeat

It might be because I am not escaping them properly but I would like the user to search by any keyword. Is there a way to get around this? I know this must be trivial to a lot of folks but I am a complete noob when it comes to regex.

Any help is appreicated.




Aucun commentaire:

Enregistrer un commentaire