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**"}
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));
来源:http://www.cnblogs.com/leee/p/5206848.html