0

I want a JavaScript regex to extract the value of an id from facebook profile URL. For example, I have a url

https://www.facebook.com/profile.php?id=100004774025067 

and I just want to extract the value after the id= which is the number 100004774025067 part only.

But In some cases I will need the user profile url from a post. For example a user posted something, and if i get the profile url link of the post then I get the link like this:

https://www.facebook.com/profile.php?id=100001883994837&hc_ref=ART7eWRecFS8mMIio66GdaH378zlJMXzisnKubh5PtgINeVwTfOil5aBIyff71OamWA 

As you can see, after the value of id there's an additional parameter specified.

I only need to get the id value, no matter what else is in the link.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
Antesoft
  • 61
  • 1
  • 10

2 Answers2

2

You can use the string as a URL and extract the id parameter using searchParams:

Without additional parameters:

var fb_url = "https://www.facebook.com/profile.php?id=100004774025067";
var url = new URL(fb_url);
var uid = url.searchParams.get("id");
console.log(uid);

With more parameters:

var fb_url = "https://www.facebook.com/profile.php?id=100004774025067&hc_ref=ART7eW";
var url = new URL(fb_url);
var uid = url.searchParams.get("id");
console.log(uid);
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
0

You can do it in the following way

function getNumber(str){
    console.log(str.match(/(?:id=)(\d+)/)[1]);
    return str.match(/(?:id=)(\d+)/)[1];
}

getNumber('https://www.facebook.com/profile.php?id=100004774025067');
getNumber('https://www.facebook.com/profile.php?id=100001883994837&hc_ref=ART7eWRecFS8mMIio66GdaH378zlJMXzisnKubh5PtgINeVwTfOil5aBIyff71OamWA ');

which matches any number after id

marvel308
  • 10,288
  • 1
  • 21
  • 32