2014-10-16 32 views
2

我有以下網址:的Javascript獲得URL查詢字符串不

url = 'http://stackoverflow.com/questions/ask?new=question' 

我該如何獲得URL沒有查詢字符串?是的,現在我正在做下面的事情,但有沒有一種方法可以做到這一點,而不是添加兩個?

window.location.origin + window.location.pathname 

回答

6

要獲取url的所有不同部分,location.protocol + '//' + location.host + location.pathname將是正確的語法。下面是其中顯示該片段託管的URL的例子:

document.body.innerHTML = "The snippet is at this web address: " + getURL(); 
 

 
function getURL() { 
 
    return location.protocol + '//' + location.host + location.pathname 
 
}

4

例如這樣的 - location.href.split("?")[0] - 分裂由?並採取所得陣列的第一個元素。即使位置中沒有?,它也可以工作 - 整個url將是數組的單個元素。

ps:downvoter - comments?不要成爲一隻雞。