Last active
December 17, 2015 21:09
-
-
Save wiky/5673022 to your computer and use it in GitHub Desktop.
provides utilities for dealing with query strings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(exports) { | |
var defaults = { | |
sep: '&', | |
eq: '=', | |
// 把querystring中的值仅按字符串解析 | |
// 值为true时,如arr=[1,2] -> {"arr": "[1,2]"} | |
beString: false | |
}; | |
var querystring = { | |
// 'str="aaa"&bool&num=123&arr=[1,2]&obj={"foo":1}' | |
// -> { "str": "aaa", bool: true, num: 123, arr: [1, 2], obj: {"foo": 1} } | |
parse: function(str, options) { | |
if (typeof str !== 'string') { | |
return {}; | |
} | |
str = str.replace(/^\s+|\s+$/, ''); | |
if (str === '') { | |
return {}; | |
} | |
if (options === true) { | |
options = { | |
beString: true | |
}; | |
} | |
options = options || {}; | |
var obj = {}, | |
pairs = str.split(options.sep || defaults.sep), | |
pair = '', | |
parts = [], | |
key, val; | |
while ((pair = pairs.shift())) { | |
parts = pair.split(options.eq || defaults.eq); | |
key = parts[0]; | |
val = parts[1]; | |
if (val) { | |
val = decodeURIComponent(val.replace(/\+/g, ' ')); | |
val = (!options.beString && JSON.parse) ? JSON.parse(val) : val; | |
} else { | |
val = true; | |
} | |
obj[key] = val; | |
} | |
return obj; | |
}, | |
// { "str": "aaa", bool: true, num: 123, arr: [1, 2], obj: {"foo": 1} } | |
// -> "str=%22aaa%22&bool=true&num=123&arr=%5B1%2C2%5D&obj=%7B%22foo%22%3A1%7D" | |
stringify: function(obj, options) { | |
if (!obj) { | |
return ''; | |
} | |
if (options === true) { | |
options = { | |
beString: true | |
}; | |
} | |
options = options || {}; | |
var pairs = [], | |
key = '', | |
val = ''; | |
for (var k in obj) { | |
if (obj.hasOwnProperty(k)) { | |
key = encodeURIComponent(k); | |
val = (!options.beString && JSON.stringify) ? JSON.stringify(obj[k]) : obj[k]; | |
val = encodeURIComponent(val); | |
pairs.push(key + (options.eq || defaults.eq) + val); | |
} | |
} | |
return pairs.join(options.sep || defaults.sep); | |
} | |
}; | |
exports.querystring = querystring; | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment