好吧,我这里有一个问题,在我的数据库中我存储了由 URL 生成的 regexPath。 我用过这个包path-to-regex
所以我将转换后的正则表达式路径作为字符串存储在数据库中,如下所示:
let path = "/v1/manager/notification/all"
let regexPath = "/^\/v1\/manager\/notification\/all(?:\/)?$/i"
我需要test()函数来检查某些条件。 当然 test() 函数需要正则表达式格式来检查正则表达式中是否存在值。我在互联网上找到的将字符串转换为正则表达式的唯一方法是:
let RegexPattern = new RegExp(regexPath)
但是 RegExp 函数将我的 i 标签视为正则表达式的一部分,它返回如下内容:
/"\/^\\\/v1\\\/manager\\\/notification\\\/all\\\/page\\=([^\\=\\\/]+?)(?:\\\/)?$\/i"/
我该如何解决这个问题?
最佳答案
您需要先提取内部正则表达式和标志。这是一个例子:
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)
关于javascript - 将字符串正则表达式转换为带有标签 i 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58098581/