1

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.

2
  • You could use new RegExp but you'd need to remove the delimiters (/) and separate the flags (ig) Commented Mar 8, 2017 at 23:02
  • 1
    Or parse them out ... with a regex. :-) Commented Mar 8, 2017 at 23:03

1 Answer 1

2

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))
})

Sign up to request clarification or add additional context in comments.

7 Comments

This version will fail if there are no flags. You might want to make those optional.
const matches = /^\/(.+)\/([a-z]*)$/g.exec(resName); maybe could work, then new RegExp(matches[0], matches[1]);, this way the flags will also be conserved
@Miquel not sure what you mean there
@Phil I see that there are also Uppercase moddifiers, so maybe the good solution for rxFinder would be /^\/(.+)\/([a-zA-Z]*)$/g. Regarding speed, if I understand well is it better to use new RegExp(matches[0], matches[1]);?
@Miquel according to the docs for JavaScript's RegExp, the flags are limited to gimuy
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.