7

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.

Harry
  • 47,045
  • 66
  • 163
  • 243
  • You need to escape the parentheses in your pattern: i.e., `(` should be `\(`, otherwise the regex engine thinks it's an opening group character. There are a number of special characters you will need to escape: a quick Google found [this](http://simonwillison.net/2006/Jan/20/escape/#p-6), for example. – Xophmeister Jan 16 '12 at 16:07
  • ...Also see: http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex – Xophmeister Jan 16 '12 at 16:08

2 Answers2

14

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

new RegExp(req.params.title.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), "i");
Community
  • 1
  • 1
  • 1
    I edited the regex to include the `|` character which means union in a regular expression body. Anyone using the version without `|` might have subtle bugs. – Mike Samuel Jan 16 '12 at 16:27
  • @WayneConrad: If you mean `escape(...)`, then no, that's different. –  Jan 16 '12 at 16:55
1

Escape it with a backslash. And test it on a site like http://rejex.heroku.com/

/cat\(22/
TuK
  • 3,396
  • 4
  • 21
  • 24