-2

I am using Node.js with mongoose for my backend. For a couple end points, I need to find items with matching item_categories and a matching item_name. However when item_name is \ the api is catches an error and returns an error message. Why is this throwing an error? I've searched online and there isn't much explaining why this happens. If item_name isn't \ then everything works correctly and the api returns a response. Also if item_name is \ ... then it works but if it is ...\ then it fails.

const items = await item.find({item_name:  new RegExp(data.item_name, "i")});
const items = await item.find({item_category:{ $all:data.item_category}, item_name: new RegExp(data.item_name, "i")});
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Snake
  • 113
  • 2
  • 10
  • Backslash is an escape character in regex. If it's trailing then it's an error, since nothing is escaped. If it's elsewhere in the string, then in signifies the next character is an escape sequence *which might change the meaning `\n` is a newline for example, `\d` means a digit. There might be other special characters in `item_name`. – VLAZ Jul 16 '21 at 06:06

1 Answers1

-1

Many characters in regular expressions have special meaning. A backslash \ is the escape character in regular expressions, and needs another character to follow it. If you just want to search for a fixed string where RegExp semantics is ignored, you need to escape the special characters.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Is there any way to search for items with \ or any of the special character in RegExp() or are those characters just offlimits? For example maybe an item_name is something like Twelve-pack coke or soda+coke. – Snake Jul 16 '21 at 06:16
  • @Snake see the link in the answer. – VLAZ Jul 16 '21 at 06:17
  • @Snake see also: https://stackoverflow.com/a/40914826 https://stackoverflow.com/a/35058756 https://stackoverflow.com/a/47439467 – VLAZ Jul 16 '21 at 06:22
  • I am kind of confused what that regex escape function does, does it replace all those escape character with // or keep the character inside //? Also I checked if the item_name is tooth/brush or tooth-brush or coke-soda and it works correctly. – Snake Jul 16 '21 at 06:28
  • If you check `Coke*Soda`, or `Coke+Soda`, or `Coke\Soda`, it will work (i.e. will not raise an error), but not in the way you think: it will match e.g. `CokSoda`, `CokeeeeeSoda` and `CokeCoda` respectively, because `+` and `*` after another character and `\` before another character all have specific meanings. The linked function prefixes all of those characters with `\`, an "escape character", which removes the special meaning from them. This makes the queries above `Coke\*Soda`, `Coke\+Soda` and `Coke\\Soda`, which match what you wanted. – Amadan Jul 16 '21 at 21:38