0

I'm using regexes with JavaScript and I'm having some trouble with one that returns me Invalid quantifier ?.

This is the code:

if(url.match(new RegExp('^https?://.+/foresee(?:-|_)surveydef\.js(?:\?)(.*)','g')) != null)

I read on other questions that I need to add a \ before the ? character but it does not fix it...

if(url.match(new RegExp('^https\?://.+/foresee(\?:-|_)surveydef\.js(\?:\?)(.*)','g')) != null)

The input url is http://marvel.com/, I just check for a match.

Valip
  • 4,440
  • 19
  • 79
  • 150
  • See http://stackoverflow.com/questions/3713290/javascript-invalid-quantifier-in-regex. Also, what is your input string? What is the expected behavior? There are potentially several issues (you are using a regex with a global modifier with `match`, that means all captured values are lost. – Wiktor Stribiżew Oct 24 '16 at 17:55
  • You need to escape those slashes. And, given that you appear to be attempting to match a URL, I'd recommend escaping the dots too. – Sebastian Lenartowicz Oct 24 '16 at 17:56
  • Ok, the `http://marvel.com/` does not contain a `?`. Using `\\?` won't help. What are the requirements? Match any URL? – Wiktor Stribiżew Oct 24 '16 at 17:58
  • @WiktorStribiżew there can be different url's to match. I need to check if the url matches the regex expression. – Valip Oct 24 '16 at 17:59
  • 1
    @SebastianLenartowicz I tried this, but the error is still there: `'events\.foreseeresults\.com\/rec\/process\?(.*)','g'` – Valip Oct 24 '16 at 17:59
  • Well, what expression should a URL match? – Wiktor Stribiżew Oct 24 '16 at 18:02
  • Works in Chrome console, with `'?'` or with `'\?'` either way –  Oct 24 '16 at 18:17
  • @WiktorStribiżew I was wrong about the code that caused the error...it was caused by another `else` statement that was on the same line (the code is not written by me). I updated my question, thank you! – Valip Oct 24 '16 at 19:01

1 Answers1

0

Fixed it with the following code:

if(url.match(new RegExp('^https?://.+/foresee(?:-|_)surveydef\.js(\\?:\?)(.*)','g'))
Valip
  • 4,440
  • 19
  • 79
  • 150
  • What are you doing with `(\\?:\?)`? Why use a RegExp constructor at all if your pattern is static? Your question is still unclear as you have not provided the input and expected output. Matching a `?` followed with an optional `:` does not make much sense. – Wiktor Stribiżew Oct 24 '16 at 19:36