PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 6, 2022

[FIXED] Why does this regex execution not return the match

 November 06, 2022     javascript, regex, regex-group     No comments   

Issue

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



Answered By - Liftoff
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing