抄自简书原创文章《javascript将url解析为json格式》
方法有二:
方法一:利用a标签来实现
function parseUrl(url) {
var a = document.createElement('a');
a.href = url;
return {
protocol: a.protocol.replace(':', ''),
hostname: a.hostname,
port: a.port,
path: a.pathname,
query: (() => {
var query = a.search.substr(1);
var queryArr = query.split('&');
var queryObj = {};
queryArr.forEach((item, index) => {
var item = item.split('=');
var key = item[0];
queryObj[key] = item[1];
})
return queryObj;
})(),
params: (() => {
var params = a.hash.substr(1);
var paramsArr = params.split('#');
return paramsArr;
})(),
}
}
var urlObj = parseUrl('http://www.baidu.com:90/search?name=liyajie&age=12#abc#bbb')
console.log(urlObj)
方法二:通过nodejs的url模块
Url {
protocol: 'http:',
slashes: true,
auth: 'user:pass',
host: 'host.com:8080',
port: '8080',
hostname: 'host.com',
hash: '#hash',
search: '?query=string',
query: 'query=string',
pathname: '/path/to/file',
path: '/path/to/file?query=string',
href: 'http://user:pass@host.com:8080/path/to/file?query=string#hash'
}