js獲取位址列url引數 親測好用
阿新 • • 發佈:2018-12-19
程式碼 :
//獲取位址列引數 function GetQueryString(str) { let LocString = String(window.document.location.href); let rs = new RegExp("(^|)" + str + "=([^&]*)(&|$)", "gi").exec(LocString), tmp; if (tmp = rs) return tmp[2]; return null; }; console.log(GetQueryString(str)) //str 引數名 //例子 //獲取 URL: http://mp.csdn.net/index.html?orderId=123 中的orderId引數 let orderid = GetQueryString('orderId'); //防止無引數時會出現報錯 做判斷 if(orderid != '' && orderid != null){ console.log(GetQueryString(orderid)) //123 } 其他引數獲取: //設定或獲取物件指定的檔名或路徑。 alert(window.location.pathname); //設定或獲取整個 URL 為字串。 alert(window.location.href); //設定或獲取與 URL 關聯的埠號碼。 alert(window.location.port); //設定或獲取 URL 的協議部分。 alert(window.location.protocol); //設定或獲取 href 屬性中在井號“#”後面的分段。 alert(window.location.hash); //設定或獲取 location 或 URL 的 hostname 和 port 號碼。 alert(window.location.host); //設定或獲取 href 屬性中跟在問號後面的部分。 alert(window.location.search);