0

ok, I have a problem here, in my database I store regexPath that made from URL. I used this package path-to-regex

so I store my converted path to regex as String in the database like this:

let path = "/v1/manager/notification/all"
let regexPath = "/^\/v1\/manager\/notification\/all(?:\/)?$/i"

and I need test() function for checking some condition. ofcourse test() function need a regex format for checking value is exists in regex.the only way I found in internet for convert string to regex is :

let RegexPattern = new RegExp(regexPath)

but RegExp function consider my i tag as a part of regex him self and it returns something like this:

/"\/^\\\/v1\\\/manager\\\/notification\\\/all\\\/page\\=([^\\=\\\/]+?)(?:\\\/)?$\/i"/

how should I solve this problem?

Babak Abadkheir
  • 2,222
  • 1
  • 19
  • 46
  • 1
    capture and remove the last values after after last `/` before passing it to new RegExp, and pass captured values as flag, `new RegExp(pattern, flag)` – Code Maniac Sep 25 '19 at 12:40
  • Could you store the regex options (the final "i" in your example) as another column in the database? – Andrew Morton Sep 25 '19 at 12:41
  • @AndrewMorton yes I can , but I consider this now I can remove the tag before storing in database as code maniac mentioned. – Babak Abadkheir Sep 25 '19 at 12:46

2 Answers2

1

Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp you need to extract the modifiers yourself and pass them in as the second parameter. You will also need to remove the leading and trailing slashes.

new RegExp(pattern[, flags])
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
1

You need to extract the inner regex and flags before. Here's an example:

const path = "/v1/manager/notification/all"
const regexPath = "/^\/v1\/manager\/notification\/all(?:\/)?$/i"

const separator = regexPath.lastIndexOf('/')

const pattern = regexPath.slice(1, separator)
const flags = regexPath.slice(separator + 1)

const regex = new RegExp(pattern, flags)

console.log('Pattern: ' + pattern)
console.log('Flags: ' + flags)
console.log('Regex: ' + regex)
Nathanael Demacon
  • 1,169
  • 7
  • 19