JavaScript获取地址栏中的链接参数

JS获取URL参数与解析
本文介绍了如何使用JavaScript和jQuery从URL中获取指定参数的方法,包括正则表达式的使用及不同场景下的解决方案。

JavaScript获取地址栏中的链接参数

 

 

<script type="text/javascript">

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null)
            return unescape(r[2]);
        return null;
    }
    //http://192.168.1.1:8083/test/upload2.jsp?id=9&name=apple
    var val=getUrlParam('id'); //输出177
    var name=getUrlParam('name'); //输出177
    
    console.log(name)
    console.log(val)
</script>

 

参考这篇博客http://caibaojian.com/177.html

 

原文链接:http://caibaojian.com/177.html

假设页面的地址是这样子的。http://caibaojian.com/p/165 ,那么我要获取最后的一个数字165,可以通过这样子的代码

var url= window.location.href;
var index = url.substring(url.lastIndexOf('/') + 1);

但是这样子有缺陷,假如我获取到的地址不是这样子的形式,而是http://caibaojian.com/tools的话,那么这个index的值就不是一个数字了。

解决方案

下面这种可能会更好呢?·

//code from http://caibaojian.com/177.html
var lastBit = url.substring(url.lastIndexOf('/') + 1).match(/[^\/]*$/)[0];
var lastDigits = url.substring(url.lastIndexOf('/') + 1).match(/[0-9]*$/)[0];  // 获取的是数字部分

获取查询值

JavaScript版:

function getUrlParam(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r!=null) return unescape(r[2]); return null;
}
//获取http://caibaojian.com/?p=177.html的p值
getUrlParam('p'); //输出177

jQuery版:

<script type="text/javascript">
(function($){
$.getUrlParam = function(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null) return unescape(r[2]); return null;
}
})(jQuery);
$(function(){
alert(window.location.href);
alert($.getUrlParam('page'));
})
</script>

http://www.caibaojian.com/front?page=5

当一个页面的地址是上面这个,那么我们使用了上面的jQuery代码,就会弹出一个数字5了。

内容扩展

对于像下面这样的网址

http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

我们可以用javascript获得其中的各个部分
1, window.location.href-----------整个URl字符串(在浏览器中就是完整的地址栏)
本例返回值: http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

2,window.location.protocol---------URL 的协议部分
本例返回值:http:

3,window.location.host----------URL 的主机部分
本例返回值:www.caibaojian.com

4,window.location.port-----URL 的端口部分
如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
本例返回值:""

5,window.location.pathname(URL 的路径部分(就是文件地址))
本例返回值:/fisker/post/0703/window.location.html

6,window.location.search-------查询(参数)部分
除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
本例返回值:?ver=1.0&id=6

7,window.location.hash-------锚点
本例返回值:#imhere

推荐文章


来源:前端开发博客

转载于:https://my.oschina.net/thomas2/blog/1612835

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值