代码已经关联到github: 链接地址 觉得不错可以顺手点个star,这里会持续分享自己的开发经验(:
解析url有两种方式,下面直接贴代码:
/**
* 方法一:正则解析url
* @param {String} url eg:https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=baidu&wd=js&oq=js
*/
const parseUrl = (url) => {
const reg = /(\w+):\/\/([\w\.]+)\:?(\d*)?([\/\.\w]*)?\??([^#]*)?#?(\S*)?/
var mattchGroup = url.match(reg)
const result = {}
result.protocol = mattchGroup[1] //=>(\w+):\/\/
result.host = mattchGroup[2] //=>([\w\.]+)\:?
result.port = mattchGroup[3] || 80 //(\d*)?
result.path = mattchGroup[4] // ([\/\.\w]*)?
result.query = mattchGroup[5] || '' //([^#]*)?
result.hash = mattchGroup[6] || '' // (\S*)?
return result
}
/**
* 方法二:a标签解析url
* @param {String} url eg:https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=baidu&wd=js&oq=js
*/
const parseUrl2 = (url) => {
let aDom = document.createElement('a')
aDom.setAttribute('href',url)
const result = {
protocol: aDom.protocol,
host: aDom.host,
port: aDom.port || 80 ,
path: aDom.pathname,
query: aDom.search,
hash: aDom.hash
}
aDom = null
return result
}
解析查询参数也有两种方式:
/**
* 方法一:正则获得查询参数
* @param {String} urlQuery eg:
*/
const parseQueryParams = (urlQuery) => {
const params = {}
urlQuery.replace(/([^?&=]+=[^&=]+)/g,function(_,k,v){
params[k]=v
})
return params
}
/**
* 方法二:分割方式获得查询参数
* @param {String} urlQuery eg:
*/
const parseQueryParams = (urlQuery) => {
let params = {}
const paramsGroup = urlQuery.split('&')
for (let item of paramsGroup) {
const paramsItemGroup = item.split('=')
if (paramsItemGroup && paramsItemGroup.length > 0) {
let paramValue = paramsItemGroup[1]
paramValue = paramValue.replace(/%2B/gi,'+')
paramValue = paramValue.replace(/%20/gi,' ')
paramValue = paramValue.replace(/%2F/gi,'/')
paramValue = paramValue.replace(/%3F/gi,'?')
paramValue = paramValue.replace(/%25/gi,'%')
paramValue = paramValue.replace(/%26/gi,'&')
paramValue = paramValue.replace(/%3D/gi,'=')
paramValue = paramValue.replace(/%23/gi,'#')
params[paramsItemGroup[0]] = paramValue
}
}
return params
}