DIV CSS 佈局教程網

JavaScript 取得 URL 各組成部分的常見方法彙總
編輯:關於JavaScript     

以 https://www.cnblogs.com/wuxibolgs329/p/6188619.html#flag?test=12345 為例,逐一取出它的組成部分。

1. 完整 URL

 var a = location.href;
 console.log(a);
 // "https://www.cnblogs.com/wuxibolgs329/p/5261577.html#flag?test=12345"

2. 域名

 var host  = window.location.host; // www.cnblogs.com
 var host2 = document.domain;      // www.cnblogs.com
 var a     = location.hostname;    // www.cnblogs.com

注意 host 含端口號,hostname 不含;本例未指定端口,所以兩者相同。

3. 協議

 var a = location.protocol;
 console.log(a); // http:

4. 端口

 var a = location.port;
 console.log(a);

5. 路徑

 var a = location.pathname;
 console.log(a);

6. 設定或讀取協議部分

var a = location.protocol;

7. 井號後面的部分

 var a = window.location.hash;
 var b = a.substr(1);
 console.log(b); // flag?test=12345

hash 返回值含 #,用 substr(1) 去掉。

8. 問號後面的查詢字串

 // 此時案例地址為 "https://www.cnblogs.com/wuxibolgs329/p/5261577.html?test=12345"
 // 得到 test=12345
 var a = location.search;
 var b = a.substr(1);
 console.log(b);

 // 若地址仍帶有 #flag,search 取不到值,需從 href 自行截取
 var a = location.href;
 var b = a.substr(a.lastIndexOf('?')+1);
 console.log(b); // test=12345

這一點很容易踩坑:search 只認問號之前的路徑部分,一旦 URL 帶 hash,就必須回到 href 手動截取。

9. 等號後面的值

 var a = location.href;
 var b = a.substring(a.lastIndexOf('=')+1);
 console.log(b); // 12345

實務上若參數較多,更推薦用 URLSearchParams 解析查詢字串,避免層層 lastIndexOf 帶來的歧義。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved