定义一个从字符串生成正则表达式的函数:
function getRegex(str) {
return new RegExp(str, "ig");
}
测试使用问号作为参数的结果, 报错了,和日志中错误相同:
getRegex("?")
VM50:2 Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat
at new RegExp ()
at getRegex (:2:12)
at :1:1
getRegex @ VM50:2
(anonymous) @ VM66:1
尝试转义问号呢?
getRegex("\?")
VM50:2 Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat
at new RegExp ()
at getRegex (:2:12)
at :1:1
getRegex @ VM50:2
(anonymous) @ VM69:1
再次使用转义, 可以了
getRegex("\\?")
/\?/gi
其他情况?
getRegex("??")
VM50:2 Uncaught SyntaxError: Invalid regular expression: /??/: Nothing to repeat
at new RegExp ()
at getRegex (:2:12)
at :1:1
getRegex @ VM50:2
(anonymous) @ VM77:1
使用中括号表示可选?
getRegex("[?]")
/[?]/gi
str="https://visteria.vnative.net/5cb08a1689d4466c7080723c?p1={your-transaction-id}&source={your-sub-aff-id}"
"https://visteria.vnative.net/5cb08a1689d4466c7080723c?p1={your-transaction-id}&source={your-sub-aff-id}"
把正则表达式用来做split的参数
aa=getRegex("[?]")
/[?]/gi
str.split(aa)
(2) ["https://visteria.vnative.net/5cb08a1689d4466c7080723c", "p1={your-transaction-id}&source={your-sub-aff-id}"]
str.split(aa)[0]
"https://visteria.vnative.net/5cb08a1689d4466c7080723c"
最后重复一次对比
aa=getRegex("?")
VM50:2 Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat
at new RegExp ()
at getRegex (:2:12)
at :1:4
getRegex @ VM50:2
(anonymous) @ VM153:1
aa=getRegex("\?")
VM50:2 Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat
at new RegExp ()
at getRegex (:2:12)
at :1:4
getRegex @ VM50:2
(anonymous) @ VM156:1
aa=getRegex("\\?")
/\?/gi
str.split(aa)[0]
"https://visteria.vnative.net/5cb08a1689d4466c7080723c"
str.split(aa)
(2) ["https://visteria.vnative.net/5cb08a1689d4466c7080723c", "p1={your-transaction-id}&source={your-sub-aff-id}"]