Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating regexp with special characters

I'm creating a query 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 title has a parenthese in it. This gives me the error:

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

The title that is being searched for is cat(22).

What's the easiest way to make the regex accept parenthesis? Thanks.

like image 751
Harry Avatar asked Jan 16 '12 16:01

Harry


1 Answers

You can escape all possible regex special characters with code borrowed from this answer.

new RegExp(req.params.title.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), "i");
like image 179
3 revs, 2 users 75%user1106925 Avatar answered Oct 10 '22 14:10

3 revs, 2 users 75%user1106925