法一:需要引入jQuery
(function ($) {
$.request = (function () {
var apiMap = {};
function request(queryStr) {
var api = {};
if (apiMap[queryStr]) { return apiMap[queryStr]; }
api.queryString = (function () {
var urlParams = {};
var e,
d = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); },
q = queryStr.substring(queryStr.indexOf('?') + 1),
r = /([^&=]+)=?([^&]*)/g;
while (e = r.exec(q)) urlParams[d(e[1])] = d(e[2]);
return urlParams;
})();
api.getUrl = function () {
var url = queryStr.substring(0, queryStr.indexOf('?') + 1);
for (var p in api.queryString) { url += p + '=' + api.queryString[p] + "&"; }
if (url.lastIndexOf('&') == url.length - 1) { return url.substring(0, url.lastIndexOf('&')); }
return url;
}
apiMap[queryStr] = api;
return api;
}
$.extend(request, request(window.location.href));
return request;
})();
}(jQuery));
用例:
var queryString = $.request(location.href).queryString;
var status=queryString.editStatus;
法二:原生js
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
用例:
var openId = GetQueryString("openId");
法三:这个考虑的比较简单的url字符串的情况,建议用以上两种写法
function GetQueryString(str){
var arr=window.location.search.substr(1).split("&");
var result="";
for(value in arr){
var temp=arr[value].split("=");
if(temp[0]==str){
result=temp[1];
return result;
}
}
}