xRobot
xRobot

Reputation: 26567

How to get the ID from this URL?

I need a way to get the ID ( 153752044713801 in this case ) of this page:

https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801

I tried this code but doen't work:

var str = 0, pagefb = 0;
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';

var re1 = /^(.+)facebook\.com\/pages\/([-\w\.]+)\/([-\w\.]+)/;

if(re1.exec(fburl)){
   str = re1.exec(fburl)[3]; 
   pagefb = str.substr(str.lastIndexOf("-") + 1);
   alert('ok');
}

Upvotes: 0

Views: 97

Answers (4)

Kaspar Lee
Kaspar Lee

Reputation: 5596

You can split the string using .split("/"). More information is availible on MDN

var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';

var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]

Basically it returns an array of the string split into multiple parts (at the character/s you put inside the brackets). The parts[parts.length - 1] will get the last item in the array parts

Demo below (Don't worry about the document..., they just print out data):

var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713‌​801/?ref=sfhsidufh';

var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]

// If first digit is ?
if (myFacebookId[0] == '?') {
    // Set myFacebookId to the second from last part
    myFacebookId = parts[parts.length - 2]
}

document.write('MyFacebookId: ' + myFacebookId)

Upvotes: 0

Alessandro
Alessandro

Reputation: 876

try:

var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split("/");
var myId = parts[parts.length-1];
alert(myId);

Upvotes: 1

Arif
Arif

Reputation: 1643

this works for me

fburl.split('/')[fburl.split('/').length-1]

Upvotes: 0

FelixSFD
FelixSFD

Reputation: 6092

Try this regular expression: ^(.+)facebook\.com\/pages\/.*\/(\d*)

(in JavaScript, you have to add "/" at the beginning and end of the pattern like you did before)

Upvotes: 0

Related Questions