window.location獲取URL資訊
阿新 • • 發佈:2020-08-27
window的location物件
-
window.location.href 整個URl字串(在瀏覽器中就是完整的位址列)
-
window.location.protocol URL 的協議部分。返回值:
http:
-
window.location.host URL 的主機部分(帶埠號)
-
window.location.port URL 的埠部分。
-
window.location.pathname URL 的路徑部分(就是檔案地址)
-
window.location.search 查詢(引數)部分。得到的是url中?部分。
除了給動態語言賦值以外,我們同樣可以給靜態頁面,並使用javascript來獲得相信應的引數值。 -
window.location.hash 錨點。得到的是url中#部分。
substr()
返回一個從指定位置開始的指定長度的子字元。
獲取URL中的查詢字串:(這裡substr設定為1,是為了把url中的?號去掉)
function getQuery(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return decodeURI(r[2]); return null; }
注:
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
(^| )代表開始
( |$)代表結束
以&或者$結尾的字串
這個正則是尋找&+url引數名字=值+&
&可以不存在。