获取地址栏参数

开发过程中,难免会遇到获取地址栏参数值的情况,处理一长串请求地址,并从中获取相关参数,需要对字符串做进一步的处理!

之前一段时间,做分享的时候,需要从地址栏获取相关的参数在本地使用,于是就封装了一个方法,用于获取地址栏指定参数的值!

 // 获取地址栏参数值
 function getQueryString(name) {
     var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
         r = window.location.search.substr(1).match(reg);
     if (r != null) return unescape(r[2]);
     return null;
 }

三目运算符简化版

getQueryStr(n) {
  let r, reg = new RegExp("(^|&)" + n + "=([^&]*)(&|$)");
  r = window.location.search.substr(1).match(reg);
  return r ? decodeURI(r[2]) : null;
}

 注:

unescape(string) 和 decodeURI(string)的区别:

unescape:通过找到形式为 %xx 和 %uxxxx 的字符序列(x 表示十六进制的数字),用 Unicode 字符 u00xx 和 uxxxx 替换这样的字符序列进行解码。

decadeURl:跟unescape功能一致,只不过ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。

 
原文地址:https://www.cnblogs.com/zxk5211/p/web_12.html