您的位置:首页 > Web前端 > JavaScript

用js获取当前页面的url的相关信息方法

2015-06-21 23:43 711 查看
当前页面对应的URL的一些属性:

( http://bbs.xxx.net/forum.php?mod=viewthread&tid=2709692&page=1&extra=#pid23817304)
1)当前页面的完整的URL: window.location.href

2)当前页面的URL的pathname: window.location.pathname (http://bbs.xxx.net/forum.php)

3)当前页面的URL的问号后面的查询部分: window.location.search (?mod=viewthread&tid=2709692&page=1&extra=#pid23817304)

4)当前页面的URL的在井号“#”后面的部分:window.location.hash (pid23817304)

5)协议:window.location.protocol

6)端口:window.location.port

7)获取查询部分某个key对应的值:

var common = {};

common.getQueryString = function(name){
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null)
return unescape(r[2]);
return null;
}


这里如何理解正则表达式:new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i") 呢?

?mod=viewthread&tid=2709692&page=1

window.location.search.substr(1) 去掉了最初的问号: ? ,得到 mod=viewthread&tid=2709692&page=1

"(^|&)" + name 表示以name开头,比如name="mod" 时,就是以'mod'开头;而当name="tid"时,就是匹配 &tid 了。

"=([^&]*)(&|$)" 中的 ([^&]*) 表示非 $ 字符可以出现任意次,也就是匹配非 & 的字符;然后最后的 (&|$) 表示最后是 & 比如name="tid"时,或者$比如name="page" 时。

8)获取所有的查询部分:

function GetRequest(){
var url = window.location.search; // 获取url中"?"符后的字串
var theRequest = {};  // 定义一个对象
if(url.indexOf("?") != -1){
var str = url.substr(1);
var strs = str.split("&");
for(var i = 0; i < strs.length; i++){
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}


将查询部分的键值对,作为一个对象返回,key为对象的属性,value为对象属性的值(其实也相当于一个map)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: