简体   繁体   中英

How to escape reqexp to find documents in MongoDB?

I've simple regexp based searching via MongoDB like:

router.get('/search', function (req, res, next) {
   var text = req.query.text;

   collection.find({text: new ReqExp(text, 'ig')}, function (err, result) {
      if (err) return next(err);

      return res.status(200).json({result: result});
   }); 
});

If user tries to search text like javascript MongoDB successfully find all documents by regular exception. But if he tried to search (javascript then MongoDB throws with the following exception:

[SyntaxError: Invalid regular expression: /(javascript/: Unterminated group]

What is the proper way to escape input text to prevent errors as above?

The problem with "(javascript" is that contains the special character "(" and it can be used as part of a pattern match expression. There are many other characters that can be part as regular expression as well: [,\\,?,+. Each of them needs to be escaped with "\\" to avoid interpretation of its special meaning. For example if the user enters "(javascript" the string "(javascript" would have been searched.

The following URL is a very good source for understanding the patterns that can be used as part of RegExp:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM