如何使用javascript/jquery从URL中删除get变量和文件名?

8
我正在研究这个问题,但是我找不到针对此特定目的的确定答案。假设我有一个URL:http://mysite.com/stuff/index.php?search=my+search ,如何获取该URL并将index.php?search=my+search从中删除,使其变为http://mysite.com/stuff/?基本上,我只想获取没有文件名或获取变量的父URL...无论URL是什么(所以我不必为每个要使用它的页面定制函数)。
因此,举个例子,如果只是http://mysite.com/silly.php?hello=ahoy,那么我只想返回http://mysite.com的根目录。
有人能帮我解决这个问题吗?我完全迷失了。
4个回答

18

尝试使用lastIndexOf("/")

var url = "http://mysite.com/stuff/index.php?search=my+search";
url = url.substring(0, url.lastIndexOf("/") + 1);
alert(url); // it will be "http://mysite.com/stuff/"

var url = "http://mysite.com/silly.php?hello=ahoy";
url = url.substring(0, url.lastIndexOf("/") + 1);
alert(url); // it will be "http://mysite.com/"

谢谢,我想现在会经常使用lastIndexOf了。 - Ian
console.log(url) 比 alert 好得多。 - Tim

2
如果您的url在str中:
newstr = str.replace(/\/[^\/]+$/,"");

newstr 现在包含字符串中最后一个 / 之前的路径。如果要保留最后一个 /,请使用:

newstr = str.replace(/\/[^\/]+$/,"/");

2

将文本按照"/"分割,丢弃最后一部分,重新组合起来,添加尾随斜杠。

var path = location.href.split('/');
path.pop();
path = path.join("/") + "/";

0
你正在寻找 location.host 或者 location.hostname。但是你是否想从完整的字符串中提取它们,而不是从当前 URL 中提取?
我再次阅读了这个问题,似乎你想要获取由以下字符串组成的内容:
location.protocol + "//" + location.host + location.pathname

对吗?


4
location.pathname 将包含 index.php - Shiplu Mokaddim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接