0

I have a regex that takes a template literal and then matches it against a CSV of conditions and links.

const regex = new RegExp(`^${condition},\/.+`, 'gi');

For example, the variable Sore throat would match

'Sore throat,/conditions/sore-throat/'

I've come across an issue where the template literal might contain brackets and therefore the regex no longer matches. So Diabetes (type 1) doesn't match

'Diabetes (type 1),/conditions/type-1-diabetes/'

I've tried removing the brackets and it's contents from the template literal but there are some cases where the brackets aren't always at the end of the string. Such as, Lactate dehydrogenase (LDH) test

'Lactate dehydrogenase (LDH) test,/conditions/ldh-test/'

I'm not too familiar with regex so apologies if this is simple but I haven't been able to find a way to escape the brackets without knowing exactly where they will be in the string, which in my case isn't possible.

kish-an
  • 75
  • 1
  • 5

1 Answers1

-1

You are trying to use a variable that might contain special characters as part of a regex string, but you /don't/ want those special characters to be interpreted using their "regex" meaning. I'm not aware of any native way to do this in Javascript regex - in Perl, you would use \Q${condition}\E, but that doesn't seem to be supported.

Instead, you should escape your condition variable before passing it into the regex, using a function like this one:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
Dan
  • 10,255
  • 2
  • 33
  • 55
  • 1
    Not by me but probably because you _cut'n pasted_ the _Short and Sweet_ answer from here https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex when it is should just be a comment. –  Sep 14 '19 at 21:29