The regular expression fails to match a string with special characters (special characters refer to:.? + $ ^ [] () {} | \ /)

The special characters are: .? + $ ^ [] () {} | \ /
Example of unsuccessful matching:

const str = '(hehe)43'
const reg = new RegExp(str,'gi')  // reg : /(hehe)43/ 括号未做转义处理
console.log(reg.test(str))   // 结果是 false

Reason for unsuccessful matching: special characters in the string in str are not escaped

If you want to match successfully, you must first escape the special characters in str.
Examples of successful matching:

const str = '(hehe)43'
// 对字符串中的特殊字符做转义处理
const str = str.replace(/([*.?+$^(){}|\\/])/g, '\\$1')  // str : "\(hehe\)43"
const reg = new RegExp(str,'gi') // reg : /\(hehe\)43/  括号已做转义处理
console.log(reg.test(str))   // 结果是 true

Guess you like

Origin blog.csdn.net/weixin_46611729/article/details/111375769