2012-02-04 50 views
8

我正在調查這個問題,但我無法找到任何這個具體目的的可靠答案。比方說,我有一個網址...如何從URL中使用javascript/jquery刪除獲取變量和文件名?

http://mysite.com/stuff/index.php?search=my+search

我怎麼能抓住這個URL和刪除的index.php?搜索=從中我+搜索,這純粹是http://mysite.com/stuff/?基本上我只是想抓住沒有文件名或獲得變量的父網址...無論什麼URL(所以我不必爲每個頁面定製我想要使用它的功能)

因此對於另外的例子,如果只是......

http://mysite.com/silly.php?hello=ahoy

我只是想回到的http://mysite.com

誰能給我一個手搞清楚了這一點?我完全失去了。

回答

17

嘗試使用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/" 

OR

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

謝謝,我想我現在會不斷地使用lastIndexOf。 – Ian 2012-02-04 22:43:16

+0

樂意幫忙.. – Aliostad 2012-02-04 22:51:35

+0

'console.log(url)'比警報好得多。 – Tim 2016-09-15 16:29:09

0

您正在查找location.hostlocation.hostname。但是,你想從完整的字符串而不是從當前的URL中提取它們嗎?

我讀的問題,再一次,它似乎想要得到它由字符串:

location.protocol + "//" + location.host + location.pathname 

吧?

+4

'location.pathname'將包含'index.php' – 2012-02-04 22:54:12

2

如果您的網址是str

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

newstr現在包含路徑到不包括在最後/字符串。爲了保持最後/,使用方法:

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

分裂「/」,放棄了最後一塊,他們一起回來了,加斜槓。

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