Home > Mobile >  Why does this regex execution not return the match
Why does this regex execution not return the match

Time:02-26

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 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?

CodePudding user response:

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"))

  • Related