Skip to content

Instantly share code, notes, and snippets.

@tvl83
Created July 29, 2017 23:41
Show Gist options
  • Save tvl83/3a41274e290d1d8f6882d8291073a4af to your computer and use it in GitHub Desktop.
Save tvl83/3a41274e290d1d8f6882d8291073a4af to your computer and use it in GitHub Desktop.
Does anyone know how to insert a variable(a string) into a regular expression statement and then take that regex expression (not a string data type) and put it in a javaobject ? I am using MongoDB (it's an already made db I am only querying against) and to query a colleciton I need to use RegEx. I have the expression I need but it needs to be dy…

when I sent a post with {"username":"blah"} as the payload I need a response of

{
    "title": /.*@blah.*/i,
    "$or": [
        {
            "body": /.*@blah.*/i
        }
    ]
}

But I get

{
    "title": "/.*@blah.*/i",
    "$or": [
        {
            "body": "/.*@blah.*/i"
        }
    ]
}

which won't work as a query.

app.post('/mentions', function(req,res){
var username = req.body.username;
var titleRegex = "/.*@"+username+".*/i";
var titleRegexObj = new RegExp(titleRegex);
var query = {
"title": titleRegex,
$or: [
{
"body": titleRegex
}
]
};
res.send(query);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment