簡體   English   中英

JavaScript中沒有任何參數如何獲得URL?

[英]How to get the URL without any parameters in JavaScript?

如果我使用:

alert(window.location.href);

我得到了包括查詢字符串在內的所有內容。 有沒有辦法獲得主要的 url 部分,例如:

http://mysite.com/somedir/somefile/

代替

http://mysite.com/somedir/somefile/?foo=bar&loo=goo

這是可能的,但您必須從object location手動構建它:

location.protocol + '//' + location.host + location.pathname

每個答案都相當復雜。 這里:

var url = window.location.href.split('?')[0];

即使一個? 不存在,它仍然會返回第一個參數,這將是您的完整 URL,減去查詢字符串。

它也與協議無關,這意味着您甚至可以將它用於 ftp、itunes.etc 等。

使用indexOf

var url = "http://mysite.com/somedir/somefile/?aa";

if (url.indexOf("?")>-1){
url = url.substr(0,url.indexOf("?"));
}

我遲到了,但我最近不得不解決這個問題,我想我會分享財富。

const url = window.location.origin + window.location.pathname
//http://example.com/somedir/somefile/

window.location.origin將為您提供基礎 url,在我們的測試案例中: http://example.com

window.location.pathname將為您提供路由路徑(在基本 url 之后),在我們的測試用例/somedir/somefile

解決方案 2

您可以簡單地執行以下操作來擺脫查詢參數。

const url = window.location.href.split('?')[0]

您可以連接originpathname ,如果存在諸如example.com:80之類的端口,也將包括在內。

location.origin + location.pathname
var url = "tp://mysite.com/somedir/somefile/?foo=bar&loo=goo"    

url.substring(0,url.indexOf("?"));

您可以使用正則表達式: window.location.href.match(/^[^\#\?]+/)[0]

使用 URL 的另一種選擇

var theUrl = new URL(window.location.href);
theUrl.search = ""; //Remove any params
theUrl //as URL object
theUrl.href //as a string

如果您查看文檔,您可以從window object 中獲取您感興趣的屬性,即

protocol + '//' + hostname + pathname

使用URL()構造函數,然后提取並連接源和路徑名。 這將自動從 url 中去除搜索(也稱為查詢)參數,只留下方案、域、端口和路徑名。

 const url = new URL('http://localhost:8080/index.html?search=foo&other=bar'); console.log(url.origin + url.pathname);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM