url基本构成如上图所示,href 即为完整的url。
以 http://www.localhost:8080/mian/index.html?id=123&psd=456#789 为例,将其解析为object格式,如下:
{
protocol: 'http:',
hostname: 'www.localhost',
port: '8080',
pathname: '/main/index.html',
search: { id: '123', psd: '456' },
hash: '#789'
}
方法一:使用内置API
var myURL = 'http://www.localhost:8080/main/index.html?id=111&psd=456#789'
function parseURL(href) {
let url = new URL(href)
let params = new URLSearchParams(url.searchParams)
let obj = new Object()
params = Object.fromEntries(params)
obj.protocol = url.protocol
obj.hostname = url.hostname
obj.port = url.port
obj.pathname = url.pathname
obj.search = params
obj.hash = url.hash
return obj
}
parseURL(myURL)
方法二:自己写函数,利用split进行分割
var myURL = 'http://www.localhost:8080/main/index.html?id=111&psd=456#789'
function parseURL(href) {
let obj = new Object()
obj.protocol = href.split('//')[0]
let hostname = href.split('//')[1]
if(hostname.indexOf(':') !== -1) {
obj.hostname = hostname.split(':')[0]
obj.port = hostname.split(':')[1].split('/')[0]
} else {
obj.hostname = hostname.split('/')[0]
obj.port = ''
}
let pathname = hostname.split('/').slice(1)
let respath = ''
for (let i = 0; i < pathname.length; i++) {
if (i < pathname.length - 1) {
respath += '/' + pathname[i]
} else if (i == pathname.length - 1) {
respath += '/' + pathname[i].split('?')[0]
}
}
obj.pathname = respath
let params = pathname[1].split('?').slice(1)[0].split('#')[0].split('&')
let resparams = {}
for (let i = 0; i < params.length; i++) {
let param = params[i].split('=')
console.log(param[0])
resparams[param[0]] = param[1]
}
obj.search = resparams
obj.hash = '#' + href.split('#')[1]
return obj
}
第二种方法太过冗长了,但思想是可以的用的。