获取url链接上的参数值的函数

function getUrlParam(name){
    var reg     = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    var result  = window.location.search.substr(1).match(reg);
    return result ? decodeURIComponent(result[2]) : null;
}

其中window.location.search为获取链接参数的方法,之前一直使用window.location.href然后使用split方法拆分。才发现window.location.search.substr(1)好像更方便。
substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符,substr(1)表示的就是截取?号,获取?之后的内容。然后用match() 检索正则表达式的匹配。

其中正则var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); "(^|&)" 这个匹配开头或&字符,整体表示寻找&+url参数名=值+&的格式,&可以不存在。这样result的内容就是检索到的匹配的内容,然后return时判断是否为空,如果不为空则result[2]在这里表示参数后的值,即返回参数值,如果为空的话就返回null。

原文地址:https://www.cnblogs.com/dxzg/p/9559665.html