I'm fiddling around with MongoDB and there is something I stumbled upon. I'd like to make a simple application in which the user can search all documents in a collection, getting the documents of which the key username
contains a certain user inputted value.
For implementing "contains" it appears a regular expression can be used. This works fine, but how can I convert user input into a regular expression? The problem is that simply doing ...
new RegExp(value);
... does not work because of special characters (like (
, [
etc.). This means the user cannot do a query containing (
this way.
I thought escaping everything would do the job:
new RegExp(value.replace(/./g, function(x) {
return "\\" + x;
});
... but it doesn't because some escaped characters are also special (e.g. \d
), so this way non-special characters become special.
I'm a bit lost how I could turn a user inputted value into a regular expression. Or is there perhaps a better way of doing a query for all documents of which a key contains a certain user inputted value?