I am using a simple regular expression-based search in MongoDB like this:
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});
});
});
When a user tries to search for text like javascript
, MongoDB successfully finds all documents with the regular expression. However, if they try to search for (javascript
, MongoDB throws the following exception:
[SyntaxError: Invalid regular expression: /(javascript/: Unterminated group]
How can I properly escape input text to prevent errors like the one above?