javascript 如何把 正则字符串 转为为正则对象?

const regStr = `
/a.*?b/
/a(.*?)c/gim
`;

// 通过如上字符串,如何拿到如下两个正则对象呢?
/a.*?b/
/a(.*?)c/gim
阅读 4k
1 个回答

1、eval

`
/a.*?b/
/a(.*?)c/gim
`.split(/\n/g).filter(item => !!item.trim()).map(item => {
    item = item.trim()
    return eval(item)
})

2、new RegExp

`
/a.*?b/
/a(.*?)c/gim
`.split(/\n/g).filter(item => !!item.trim()).map(item => {
    item = item.trim()
    let str = item.replace(/^\/(.*)\/([a-z]*)$/, '$1')
    let args = item.replace(/^\/(.*)\/([a-z]*)$/, '$2')
    return new RegExp(str, args)
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题