动态正则中的动态范围

let array = [

"`","~","!","@","#","$","%","^","&","*","(",")","_","=","+",

"[","{","\]","}","\\","|",";",":","'","\"",",","<",".",">","\/","?"

]

console.log(new RegExp(`[${array.join("")}]`, "i").test("~123")) // false

我想通过筛选数组生成动态的非法字符正则检测,但是动态正则并没有生效,请问如何才能生效?

生效代码

let array = [

// 英文

"`","~","!","@","#","$","%","^","&","*","(",")","-","_","=","+",

"[","{","]","}","\\","|",";",":","'","\"",",","<",".",">","/","?",

// 中文

"·","!","¥","…","(",")","—","【","】","、",";",":","‘","’","“","”",",","《","。","》","?"

]

for (let index = 0; index < array.length; index++) {

// 测试

console.log(new RegExp(`[${array.join("\\")}]`, "im").test(` 123 ${array[index]} 456 `))

}

回答

看图
动态正则中的动态范围
所以
是你的配置写错了

所有需要转义的里面的\都要转义
例如
'\[' -> '\\['
'\\' -> '\\\\'
'\/' -> '\\/'
等等

以上是 动态正则中的动态范围 的全部内容, 来源链接: utcz.com/a/60379.html

回到顶部