-1

I have this string:

var str = "https://www.mysite.se/this-match?ba=11"

I need to match it exactly (between / and ?), so only this-match matches, not this-ma or anything (shorter) that is contained in this-match. I.e:

var myre = new RegExp('\/this-ma\?');

Still matches:

myre.exec(str)[0]
"/this-ma"

How can I avoid that a shorter string contained in this-match does give a match?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
user1665355
  • 3,324
  • 8
  • 44
  • 84

1 Answers1

2

The definition of your regex is wrong. You'd think that \? would match literal ? character, instead of being non-greedy modifier. Not true. Quite the opposite, in fact.

var myre = new RegExp('\/this-ma\?');
> /\/this-ma?/

The backslash here works within the string literal, and outputs single ? to regex, which becomes non-greedy modifier. Use the regex literal.

var myre = /\/this-ma\?/
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367