HTML判断是PC端还是手机端,以及获取url参数

方法一(网上大部分的方法):

<script type="text/javascript">
	var sUserAgent = navigator.userAgent.toLowerCase();
	if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(sUserAgent)) {
	    //移动端            
	} else {
	    //pc端           
	}
</script>

方法二(自己项目里试出来的,不一定适用):
PC端window.location.hash是空的,移动端window.location.search是空的

<script type="text/javascript">
	//正则表达式
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	if(window.location.search == null || window.location.search == ""){
		//移动端(substr()是删除“?”及前面的字符串)
		var r = window.location.hash.substr(14).match(reg);
		console.log(r);
	}else{
	    //PC端
	    var r = window.location.search.substr(1).match(reg);
	    console.log(r);
	}  
	if (r != null) {
        return decodeURI(r[2]);
    }
    return null;
</script>

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中#部分。

var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");

(^|)代表开始
(|&)代表结束
以&或者$结尾的字符串
这个正则是寻找&+url参数名字=值+&
&可以不存在。

window.location.search.substr(1).match(reg);

(1) location是包含了相关的url的信息,它是windown的一部分。
(2) search是一个可以查询的属性,可以查询?之后的部分。
(3) substr(1)是为了去掉第一个?
(4) match()是你要匹配的部分 后面可以是正则表达式。
(5) return unescpe(r[2]) 返回的值 一个数组。
(6) 这里是开始匹配,找到了返回对应url值,没找到返回null。

作者:钻石悦
链接:https://www.jianshu.com/p/f988e4ebd627
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值