使用javascript解析链接中的额外信息

时间:2014-07-05 23:04:38

标签: javascript regex facebook

我有来自facebook Feed的这个链接输出:

http://l.facebook.com/l.php?u=http%3A%2F%2Fwww.theguardian.com%2Ftravel%2F2014%2Fapr%2F25%2Fitaly-puglia-salento-region&h=2AQF4oNrg&s=1

我需要这样的最终输出:

http://www.theguardian.com/travel/2014/apr/25/italy-puglia-salento-region

基本上我有一点要删除:

 http://l.facebook.com/l.php?u=

我在javascript中尝试使用正则表达式但不熟悉它:

Body = document.getElementsByTagName("body")[0].innerHTML;
regex = ???
Matches = regex.exec(Body);

关于如何使其发挥作用的任何想法?

3 个答案:

答案 0 :(得分:1)

使用此:

function extractLinkFromFb(fbLink) {
    var encodedUri = fbLink.split('?u=');
    return decodeURIComponent(encodedUri[1]);
}

var link = 'http://l.facebook.com/l.php?u=http%3A%2F%2Fwww.theguardian.com%2Ftravel%2F2014%2Fapr%2F25%2Fitaly-puglia-salento-region&h=2AQF4oNrg&s=1';


var myExtractedLink = extractLinkFromFb(link);

函数extractLinkFromFb()将返回您的链接。

答案 1 :(得分:0)

在解码网址之前,您可以使用此正则表达式获取所需的内容:

var myregex = /u=([^&#\s]+)/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
    thematch = matchArray[1];
} else {
    thematch = "";
}
  • 正则表达式中的括号捕获与第1组的匹配
  • u=用作分隔符,但未在第1组
  • 中捕获
  • [^&#\s]匹配一个不是&#或空白字符的字符。调整以适应。
  • +量词匹配一个或多个这些字符

答案 2 :(得分:0)

var url = 'http://l.facebook.com/l.php?u=http%3A%2F%2Fwww.theguardian.com%2Ftravel%2F2014%2Fapr%2F25%2Fitaly-puglia-salento-region&h=2AQF4oNrg&s=1';
            var str1 = "http://l.facebook.com/l.php?u=";
            var str2 = "&h=2AQF4oNrg&s=1";


            var url = url.replace(str1, ""); 
            var url=url.split("&h=")
            var uri_dec = decodeURIComponent(url[0]); // =http://www.theguardian.com/travel/2014/apr/25/italy-puglia-salento-region
            //alert (uri_dec);
            //console.log (uri_dec);