H5W3
当前位置:H5W3 > 问答 > 正文

动态正则中的动态范围

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 `))
}

回答

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

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

未经允许不得转载:H5W3 » 动态正则中的动态范围

赞 (0)

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址