0

I've come across this regex in a search results pagination tutorial, but it doesn't really explain what function the regex helper (they call "escapeRegex") provides.

string.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")

Can anyone explain what it does (or is trying to do)?

Ashh
  • 36,647
  • 11
  • 71
  • 96
FrugalTPH
  • 513
  • 1
  • 5
  • 21
  • Note that `,`, `#` and `\s` (whitespace) are nnot special in JS regex that does not support free spacing (comment) mode, so no idea why these chars are escaped. Also, `-` is not special outside a character class, it should not be escaped either. – Wiktor Stribiżew Jan 14 '20 at 11:37
  • @WiktorStribiżew yeah, it puzzled me as well. Honestly, the only explanation I have is that it's escaping input that would be regex but it `escapeRegex` means "this is the regex for replacing stuff" or "escape stuff using regex". Whatever it's escaping *for* would require escaped `#` and `,` and spaces as well as some characters that happen to overlap with special characters in regular expressions. I visited the link and it's not even much clearer (at least without reading a lot more). It describes it as "Function uses Regular Expressions (RegEx) and it escapes a lot of characters." – VLAZ Jan 14 '20 at 11:41
  • @WiktorStribiżew actually, I found the actual usage. It's `new RegExp(escapeRegex(req.query.search), 'gi');` So, it *does* take input and convert it to regex. I'm not sure why, considering they strip away anything regex related. It seems like a weird way to do case-insensitive plain-text search. – VLAZ Jan 14 '20 at 11:44
  • 2
    @VLAZ That means there is a bug in that code. – Wiktor Stribiżew Jan 14 '20 at 11:45
  • Yeah I thought that tutorial seemed a bit iffy, for what it was trying to do. I'll disregard that part. – FrugalTPH Jan 14 '20 at 11:51
  • I've also just realised that lodash has a regexEscape function, and I'm already using lodash elsewhere, so I'll just use that I think, if/when I need it. – FrugalTPH Jan 14 '20 at 11:52

0 Answers0