2012-09-16 53 views
0

我想创建一个运行javascript的书签。 它将从我使用的游戏论坛获取一部分网址,并将用户带到其编辑页面。如何获取URL的一部分并将用户重定向到包含该URL部分的URL?

的文章的网址可能是这样的 - 例如http://www.roblox.com/Forum/ShowPost.aspx?PostID=78212279

你看到帖子ID位?我想获得该号码,并将用户重定向到: http://www.roblox.com/Forum/EditPost.aspx?PostID=[NUMBER GOES HERE]

所以我想获得一部分网址并将其放入PostID中。

任何人都可以帮忙吗?

回答

0

使用javascript:

document.location = document.location.href.replace('ShowPost', 'EditPost'); 
+0

谢谢!我所需要的就是这个。 –

0

这里是你的书签:

<a href="javascript:location.href='EditPost.aspx'+location.search" onclick="alert('Drag this to your bookmarks bar');">Edit Post</a> 
0

一个URL的查询字符串是通过window.location.search可用。所以,如果你的页面http://www.roblox.com/Forum/ShowPost.aspx?PostID=78212279

var query = location.search; // ?PostID=78212279 

现在我们需要的查询字符串分割成键值对的。每个键值对由&分隔,并且一对中的每个键和值由=定界。我们还需要考虑到键值对在查询字符串中也被编码。下面是一个会照顾所有这一切对我们来说并返回一个对象,其属性代表在查询字符串的键值对的函数

function getQueryString() { 
    var result = {}, 
     query= location.search.substr(1).split('&'), 
     len = query.length, 
     keyValue = []; 

    while (len--) { 
     keyValue = query[len].split('='); 

     if (keyValue[1].length) { 
      result[decodeURIComponent(keyValue[0])] = decodeURIComponent(keyValue[1]); 
     } 
    } 
    return result; 
} 
现在用这个有问题的网页上

,我们可以得到在PostID查询字符串

var query = getQueryString(); 

query.PostID; // 78212279 
0

您可以使用正则表达式。

var re = /^https?:\/\/.+?\?.*?PostID=(\d+)/; 

function getPostId(url) { 
    var matches = re.exec(url); 
    return matches ? matches[1] : null; 
} 

DEMO