Search code examples
javascriptregexregex-lookaroundslookbehind

Javascript regex with lookahead and lookbehind being wrong?


I'm using the following regex to match the word 'stores' between '/' and '?' with a possible forward slash '/' before the '?' but for some reason it fails saying there's an invalid quantifier. Any idea why it might be wrong and quatifier is that? I tried removing '/?' but it still says the same thing.

var n=str.match(/(?<=\/)stores\/?(?=\?)/);

Thanks!


Solution

  • I think this is the invalid part: (?<=/) - javascript's lookahead is (?=y); it doesn't support lookbehinds, which is what I'm assuming you were trying to use. This regex should work though:

    \/stores\/?\?
    

    which matches:

    a forward slash,

    followed by the string 'stores',

    followed by zero or one forward slash,

    followed by a question mark.