正则表达式-regex-正则 new RegExp(字符串,'模式') 将字符串转换为指定模式的正则表达式

  1. 如果字符串中含有正则中的不能出现的特殊字符串, 则会进行转义
  2. /会被转义为\/
  3. 正则中的转义字符因为会被字符串转义,所以需要转义两次
  4. 示例:
  5. child::将字符串转为正则中的字符串

实例:

new RegExp('hi','g') ===/hi/g new RegExp('/') === /\//

const str = `(\r?\n|\r)`
const reg = new RegExp(str)
console.log(reg); /* /(\r?\n|\r)/ */

解析完整的正则表达式格式的字符串

// 将带有/和模式的字符串转换为正则表达式
const regexp = new RegExp(regexpString.slice(1, regexpString.lastIndexOf('/')), regexpString.slice(regexpString.lastIndexOf('/') + 1))