詳解javascript獲取url信息的常見方法
更新時間:2016年12月19日 12:37:27 作者:wxwx123
本篇文章主要對javascript獲取url信息的常見方法進行介紹,具有很好的參考價值,需要的朋友一起來看下吧
先以“http://www.cnblogs.com/wuxibolgs329/p/6188619.html#flag?test=12345”為例,然后獲得它的各個組成部分。
1、獲取頁面完整的url
var a=location.href; console.log(a); // “http://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
3、獲取url協議
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、設置或獲取 URL 的協議部分
var a = location.protocol;
7、獲取#后的部分
var a=window.location.hash; var b=a.substr(1); console.log(b); // flag?test=12345
8、獲取 href 屬性中跟在問號?后面的部分
// 此時案例地址變?yōu)椤癶ttp://www.cnblogs.com/wuxibolgs329/p/5261577.html?test=12345”。得到 test=12345
var a=location.search;
var b=a.substr(1);
console.log(b);
//如果案例依舊是“http://www.cnblogs.com/wuxibolgs329/p/5261577.html#flag?test=12345”,則需下面的寫法,得到 test=12345
var a=location.href;
var b=a.substr(a.lastIndexOf('?')+1);
console.log(b);
9、獲取 = 號后面的部分
var a=location.href;
var b=a.substring(a.lastIndexOf('=')+1);
console.log(b); // 12345
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關文章
深入理解javascript嚴格模式(Strict Mode)
Strict mode是JavaScript1.8.5引進的技術,但還沒有瀏覽器確實可靠的實現了嚴格模式,所以使用時要小心并且多測試。Strict mode可以應用于整個腳本,也可以適合于單個函數。2014-11-11

