We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
写一个程序parse,解析下面的queryString,返回一个对象
parse
queryString
console.log(parse('a=1&b=2&c=3')) // => { a: '1', b: '2', c: '3' } console.log(parse('a&b&c')) // => {} console.log(parse('a[name][second]=careteen&a[company]=sohu&b=y')) // => { a: { name: { second: 'careteen' }, company: 'sohu' }, b: 'y' } console.log(parse('color=Deep%20Blue')) // => { color: 'Deep Blue' } console.log(parse('a[0]=1&a[1]=2')) // => { a: [ '1', '2' ] }
首先要先了解url参数的规则
url参数
&
=
encodeURIComponent
a[name][second]=careteen&a[company]=sohu&b=y
a[0]=1&a[1]=2
针对上述分析其规则,解析一个URL需要考虑诸多情况。
具体代码和测试用例实现
下面给出具体实现
/** * @desc 解析URL * @param {String} str * @param {Object} options * @param {String} options.delimiter // 分隔符 */ const parse = (str, options = {}) => { let config = Object.assign({ delimiter: '&' }, options) return str.split(config.delimiter).reduce((ret, cur) => { let [key, value] = cur.split('=') if (!value) return ret // ret[key] = value deepSet(ret, key, value) return ret }, {}) }
辅助函数
/** * @desc 辅助函数 深层级设置 */ const deepSet = (ret, key, value) => { /* eslint-disable */ let path = key.split(/[\[\]]/g).filter(item => !!item) // console.log(path) let i = 0 for (; i < path.length - 1; i++) { if (ret[path[i]] === undefined) { if (path[i + 1].match(/^\d+$/)) { ret[path[i]] = [] } else { ret[path[i]] = {} } } ret = ret[path[i]] } ret[path[i]] = decodeURIComponent(value) // console.log(ret) }
测试用例
解析字符串看似简单,实则考察诸多知识点
reduce
URL
The text was updated successfully, but these errors were encountered:
No branches or pull requests
解析字符串
前言
写一个程序
parse
,解析下面的queryString
,返回一个对象分析
首先要先了解
url参数
的规则&
或其他字符进行分割,且以=
分割键值对&
和=
分割时可能没有值=
后面的值可能已经encodeURIComponent
转码,需要解码a[name][second]=careteen&a[company]=sohu&b=y
,需要按层级设置对象a[0]=1&a[1]=2
,此时应该处理返回成数组实现
针对上述分析其规则,解析一个URL需要考虑诸多情况。
具体代码和测试用例实现
下面给出具体实现
辅助函数
测试用例
总结
解析字符串看似简单,实则考察诸多知识点
reduce
去简化流程URL
规则满足各种需求The text was updated successfully, but these errors were encountered: