- window.location.href:這個屬性返回當(dāng)前窗口(當(dāng)前頁面、iframe)的完整 URL。
- window.parent.location.href 是上一層頁面跳轉(zhuǎn)url
- window.top.location.href 是最外層的頁面跳轉(zhuǎn)url
- document.URL:這個屬性也可以用來獲取當(dāng)前窗口的完整 URL
- window.location.toString():使用該方法同樣可以獲得當(dāng)前頁面的完整 URL。
- window.location.protocol + '//' + window.location.host + window.location.pathname:通過拼接協(xié)議、主機和路徑信息,我們也能夠構(gòu)建出完整的 URL 地址。
console.log(window.location.protocol + '//' + window.location.host + window.location.pathname);
- 使用正則表達(dá)式提?。?如果你只需要從URL中提取特定部分,比如域名或查詢參數(shù)等,你可以使用正則表達(dá)式配合match()方法進(jìn)行匹配獲取。例如:
const url = window.top.location.href; const domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/im)[1]; console.log(domain); // 輸出域名部分 const params = {}; url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) { params[key] = decodeURIComponent(value); }); console.log(params); // 輸出包含查詢參數(shù)鍵值對組成的對象
文章來源地址http://www.zghlxwxcb.cn/news/detail-714583.html
文章來源:http://www.zghlxwxcb.cn/news/detail-714583.html
到了這里,關(guān)于js 獲取url的多種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!