简体   繁体   中英

How to make a regex call with a '&' or '?' as first character

I am trying to make a regex call with the following string:

if ((/&timeout=true|?scn=header/i).test(url))

... and the statement continues. I am receiving this error in the console:

Uncaught SyntaxError: Invalid regular expression: /&timeout=true|?scn=header/ : Nothing to repeat

How do I properly make this statement?

您必须转义问号字符,因为它是正则表达式运算符:

if ((/&timeout=true|\?scn=header/i).test(url))

The problem is that ? has a special meaning of repeat zero or one times , hence the error. Just escape it:

/&timeout=true|\?scn=header/

Try /(&timeout=true|\\?scn=header)/i

? is a special character in regex so you need to escape it

Demo: http://www.regexr.com/3bqlu

Try this:

/[&\\?]timeout=true|[&\\?]scn=header/

It matches both

http://example.com/file.html?scn=header&timeout=true
http://example.com/file.html?timeout=true&scn=header

because we don't know which parameter comes first

这似乎有效

/\\&timeout=true|\\/?scn=header/i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM