Creating a regular expression with special characters

I create a request for mongodb:

app.get('content/:title', function(req, res) { var regexp = new RegExp(req.params.title, 'i'); db.find({ "title": regexp, }).toArray(function(err, array) { res.send(array); }); }); 

But sometimes the header has a parent column in it. This gives me an error:

 SyntaxError: Invalid regular expression: /cat(22/: Unterminated group at new RegExp (unknown source) 

The name that is being searched is cat (22).

What is the easiest way to force a regex to take parentheses? Thanks.

+4
source share
2 answers

You can avoid all possible special regular expression characters with code borrowed from this answer .

 new RegExp(req.params.title.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), "i"); 
+10
source

Escape with a backslash. And test it on a website, for example http://rejex.heroku.com/

 /cat\(22/ 
+1
source

Source: https://habr.com/ru/post/1391283/


All Articles