使用Javascript快速获取URL参数

首先:原文在这   Quick Tip: Get URL Parameters with JavaScript
 function getAllUrlParams(url) {

            var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

            var obj = {};

            if (queryString) {

                queryString = queryString.split('#')[0];

                var arr = queryString.split('&');

                for (var i = 0; i < arr.length; i++) {

                    var a = arr[i].split('=');

                    var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v) {
paramNum = v.slice(1, -1);
return '';
}); var paramValue = typeof(a[1]) === 'undefined' ? "" : a[1]; paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();
if (obj[paramName]) {
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
if (typeof paramNum === 'undefined') {
obj[paramName].push(paramValue);
} else {
obj[paramName][paramNum] = paramValue;
}
} else {
obj[paramName] = paramValue;
}
}
}
return obj;
}

  

在这里小小的改动了一下
      // set parameter value (use 'true' if empty)
var paramValue = typeof(a[1])==='undefined' ? true : a[1]; // (optional) keep case consistent
paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();

Optionally, you can set all parameter names and values to lowercase. That way, you can avoid situations where someone sends traffic to a url with example=TRUE instead of example=true and your script breaks (I’ve seen this happen). However, if your query string needs to be case sensitive, feel free to omit this part

paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();

  在原文中,如果参数对象值为空,就返回个布尔值。但显然 paramValue.toLowerCase(),不允许你这样做。

  整篇感觉还是蛮不错的~~

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

以上

上一篇:Web开发初探之JavaScript 快速入门


下一篇:标准库String类