1,
這個題目不約而同的出現在了多家公司的面試題中,當然也是因為太過於典型,解決方案無非就是拆字符或者用正則匹配來解決,我個人強烈建議用正則匹配,因為url允許用戶隨意輸入,如果用拆字符的方式,有任何一處沒有考慮到容錯,就會導致整個js都報錯。而正則就沒有這個問題,他只匹配出正確的配對,非法的全部過濾掉,簡單,方便。
實現代碼:
function getQueryObject(url) {
url = url == null ? window.location.href : url;
var search = url.substring(url.lastIndexOf("?") + 1);
var obj = {};
var reg = /([^?&=]+)=([^?&=]*)/g;
search.replace(reg, function (rs, $1, $2) {
var name = decodeURIComponent($1);
var val = decodeURIComponent($2);
val = String(val);
obj[name] = val;
return rs;
});
return obj;
}
getQueryObject("http://www.cnblogs.com/leee/p/4456840.html?name=1&dd=ddd**")
Object {name: "1", dd: "ddd**"}
-----------------------------2016/11/10跟新------------------------------------
2,將對象轉化成url參數。fetch
function param(a) {
var s = [], rbracket = /\[\]$/,
isArray = function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}, add = function (k, v) {
v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v);
}, buildParams = function (prefix, obj) {
var i, len, key;
if (prefix) {
if (isArray(obj)) {
for (i = 0, len = obj.length; i < len; i++) {
if (rbracket.test(prefix)) {
add(prefix, obj[i]);
} else {
buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i]);
}
}
} else if (obj && String(obj) === '[object Object]') {
for (key in obj) {
buildParams(prefix + '[' + key + ']', obj[key]);
}
} else {
add(prefix, obj);
}
} else if (isArray(obj)) {
for (i = 0, len = obj.length; i < len; i++) {
add(obj[i].name, obj[i].value);
}
} else {
for (key in obj) {
buildParams(key, obj[key]);
}
}
return s;
};
return buildParams('', a).join('&').replace(/%20/g, '+');
}
用到此方法
3 $.param和上述param方法一樣
decodeURIComponent($.param(defaults))
var defaults={
_c:'resource_hub_reports',
_l:3,
_log:JSON.stringify({s0:1})
}
var url = 'http://log.17zuoye.net/log?'+decodeURIComponent($.param(defaults));
