Search code examples
javascriptregexregex-group

Why does this regex execution not return the match


My regex is:

let a = new RegExp("(?:https?:)?\/\/(?:www\.)?(?:facebook|fb)\.com\/(?<profile>(?![A-z]+\.php)(?!marketplace|gaming|watch|me|messages|help|search|groups)[\w.\-]+)\/?", "g")

It's basically a modification of the one seen here for facebook to extract the username from a facebook url.

My test string is https://facebook.com/peterparker and my code is:

a.exec("https://facebook.com/peterparker")

When I try this in RegExr, it works fine. It shows the correct group captured (peterparker).

regexr behaviour

Yet, when I try the same code in Google Chrome's console, the code returns null:

google chrome console

Why doesn't it show up in the chrome console?


Solution

  • Since you're creating your regex from a string, you have to escape your backslashes.

    let a = new RegExp("(?:https?:)?\/\/(?:www\.)?(?:facebook|fb)\\.com\/(?<profile>(?![A-z]+\\.php)(?!marketplace|gaming|watch|me|messages|help|search|groups)[\\w.\\-]+)\\/?", "g")
    console.log(a.exec("https://facebook.com/peterparker"))

    Creating it inline does not have this problem.

    let a = /(?:https?:)?\/\/(?:www\.)?(?:facebook|fb)\.com\/(?<profile>(?![A-z]+\.php)(?!marketplace|gaming|watch|me|messages|help|search|groups)[\w.\-]+)\/?/g
    console.log(a.exec("https://facebook.com/peterparker"))