如何从网址获取网页的ID?

时间:2015-12-30 15:40:36

标签: javascript facebook-graph-api

I need to get this: 1606321809619553

From that: https://www.facebook.com/Free-Travel-Vacations-1606321809619553/?ref=br_rs

This: barackobama

From that: https://www.facebook.com/barackobama/

and This: barackobama

From that: https://www.facebook.com/barackobama

我试过这段代码:

identifier = url.substring(url.lastIndexOf("/"))

但只有在没有最终的斜杠网址时才会起作用(如上面的最后一种情况)。

2 个答案:

答案 0 :(得分:0)

你可以利用regexp

var re = /^https:\/\/www\.facebook\.com\/([-\w]+)/;

re.exec("https://www.facebook.com/Free-Travel-Vacations-1606321809619553/?ref=br_rs")[1]
=> "Free-Travel-Vacations-1606321809619553" //then use string manipulation

re.exec("https://www.facebook.com/barackobama/")[1]
=> "barackobama"

re.exec("https://www.facebook.com/barackobama")[1]
=> "barackobama"

答案 1 :(得分:0)

这是一个可以执行您想要的功能,使用regular expressions和替换运算符|来处理这两种情况:



function getIdFromFBUrl(url) {
    var regexp = /^https?:\/\/(www\.)?facebook\.[a-z]+\/((?:[a-zA-Z-]*)([0-9]+)|([a-z]*))/;
    var match = url.match(regexp);
    var id = match[3] || match[4];
    return id;
}


// Tests:

var tests = [
  "https://www.facebook.com/Free-Travel-Vacations-1606321809619553/?ref=br_rs",
  "https://www.facebook.com/barackobama/",
  "https://www.facebook.com/barackobama"
];

tests.forEach(function(url) {
    document.write(url + '<br>=> ' + getIdFromFBUrl(url) + '<br><br>');
});
&#13;
&#13;
&#13;