简体   繁体   中英

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.

您可以使用从此答案中借用的代码来转义所有可能的正则表达式特殊字符。

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

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

/cat\(22/

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