2013-05-07 49 views
6

如何在沒有頁面的情況下使用Javascript或jQuery獲取當前網址。如何在沒有頁面的情況下獲取當前網址在javascript或jQuery中

例如,如果網址是:

http://www.abc.com/music/pop.aspx

我想沒有頁面的完整路徑所以像:

http://www.abc.com/music/

沒有必要擔心參數。

感謝

+1

可能的重複:http://stackoverflow.com/questions/9513736/current-url-without-parameters-hash-https – 2013-05-07 11:27:37

+0

window.location.hostname + window.location.pathname – 2013-05-07 11:30:46

+0

@NickN。這篇文章是關於刪除參數。答案仍然有我想刪除的網頁名稱。謝謝。 – lawphotog 2013-05-07 12:58:19

回答

12

您可以使用substring()提取URL所需的部分。

Live Demo

urlBase = url.substring(0, url.lastIndexOf('/')+1); 

您可以用window.location.href獲取當前URL

urlBase = location.href.substring(0, location.href.lastIndexOf("/")+1) 
+0

+1,最好是這樣寫:'url.substring(0,url.lastIndexOf('/')+ 1);' – 2013-05-07 11:31:20

+0

謝謝@ Siamak.A.M,真好。 – Adil 2013-05-07 11:33:01

+0

非常感謝Adil – lawphotog 2013-05-07 12:55:55

4

使用window.locationsubstring

location.href.substring(0, location.href.lastIndexOf("/")) 
2

這些答案都很好。對於其他人誰來到此地後,想完全封裝的答案,我想我會扯在一起的功能

function locationHREFWithoutResource() { 
    var pathWORes = location.pathname.substring(0, location.pathname.lastIndexOf("/")+1); 
    var protoWDom = location.href.substr(0, location.href.indexOf("/", 8)); 
    return protoWDom + pathWORes; 
}; 
着想

這將返回整個URL(HREF)到最後的目錄,包括結尾的斜線。我通過訪問站點並在控​​制臺中放置函數然後調用它來測試它跨越多個不同的URL。一些例子和結果:

http://meyerweb.com/eric/tools/dencoder/ 
    -> "http://meyerweb.com/eric/tools/dencoder/" 

https://www.google.com/ 
    -> "https://www.google.com/"` 

http://stackoverflow.com/questions/16417791/how-to-get-current-url-without-page-in-javascript-or-jquery 
    -> "http://stackoverflow.com/questions/16417791/" 

最後一個就是這個頁面。

相關問題