/**
* 将url解析为Object
* @author SevensChan <chanhaozi@gmail.com>
* @param {String} url字符串
* @return {Object} url解析对象
*/
function parseUrl (url) {
// Decode URI
const urlStr = decodeURI(url) || ''
// Check URL
if (!isValidURL(urlStr)) {
throw new Error(`Type Error: '${url} is not a valid url.'`)
}
// Split URL
const [protocol, urls] = url.split('://')
const [paths, queries] = urls.split('?')
const [host, ...path] = paths.split('/')
const [queriesStr, hash] = queries.split('#')
const query = {}
queriesStr.split('&').forEach(ele => {
if (ele.length === 0) return
const [key, val] = ele.split('=')
query[key] = val
})
// Return Result
return {
protocol,
host,
path: path && path.length > 0 ? `/${path.join('/')}` : '/',
query,
hash
}
}
function isValidURL (url) {
var reg=/(http|https|ftp):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/
return reg.test(url)
}
// Test Case
let res = parseUrl('http://www.xiyanghui.com/product/list?id=123456&sort=discount#title')
console.log(JSON.stringify(res))
console.log(res.protocol === 'http')
console.log(res.host === 'www.xiyanghui.com')
console.log(res.path === '/product/list')
console.log(Object.keys(res.query).length === 2)
console.log(res.hash === 'title')
res = parseUrl('https://www.xiyanghui.com?#test')
console.log(JSON.stringify(res))
console.log(res.protocol === 'https')
console.log(res.host === 'www.xiyanghui.com')
console.log(res.path === '/')
console.log(Object.keys(res.query).length === 0)
console.log(res.hash === 'test')
console