Pregunta

using Mongodb in my meteor application I am making a query using regular expression to check if the name or code is already available in the database or not. In my string all the numbers and special character are included. But when regular expression finds a special character ++ in the string it is giving the error

Exception while invoking method
'createSubject' SyntaxError: Invalid regular expression: /^C++$/: Nothing to repeat

I20140109-13:15:21.277(5.5)? at new RegExp ()

my code is

var code_regex = new RegExp(["^",code,"$"].join(""),"i");
var curr = Meteor.curri.findOne({code: code_regex});

It is working fine with the strings but i tried C++ as the code and it produce the above error.

¿Fue útil?

Solución

You need to escape your characters because C++ is part of the regular expression, with + being to look for more matches of the prior expression.

From : How to escape regular expression special characters using javascript?

RegExp.escape = function(text) {
   return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

var code_regex = new RegExp(["^",
                             RegExp.escape(code),
                             "$"].join(""),"i");
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top