-1

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?

callmekatootie
  • 10,989
  • 15
  • 69
  • 104

1 Answers1

1

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"))
Liftoff
  • 24,717
  • 13
  • 66
  • 119