Reputation: 8969
I'm using mongodb to store data. I would like to store complete regular expressions as strings:
{
permissions: [{
resName: '/user[1-5]/ig',
isRegex: true
}]
}
I know there is the module mongoose-regexp
which can store RegExp, but I would like to store regex and strings in the same field.
I've achieved it using eval(user.permissions[i].resName).test(resName)
. I would like to know if this is the correct approach and if there is any alternative (i.e. using new RegExp(...)
)
EDIT
I'm trying to avoid eval
as this field is comming from user input and it could be a problem if something malitious is sent to db.
Upvotes: 1
Views: 65
Reputation: 164798
This should get you there
const rxFinder = /^\/(.+)\/((g|i|m|u|y)*)$/
const resName = '/user[1-5]/ig'
const resRx = new RegExp(...rxFinder.exec(resName).slice(1))
console.info(resRx)
const testStrings = ['String for User5, eh', 'Bad User7 string']
testStrings.forEach(str => {
console.info(JSON.stringify(str), 'is a match:', resRx.test(str))
})
Upvotes: 2