// 实现一个方法queryURLParameter获取一个URL地址问号?后面的参数信息
let url = 'http://www.baidu.com?id=123&name=hello&sex=1#box'
/*
期望结果:{
id:123,
name:'hello',
sex: 1
}
*/
// 1.获取问号后面的值
let askIndex = url.indexOf('?')
let wellIndex = url.indexOf('#')
let askText = url.substring(askIndex + 1,wellIndex)
let wellText = url.substring(wellIndex + 1)
console.log(askText) // =>id=123&name=hello&sex=1
console.log(wellText) // =>box
// 2.问号后面值的详细处理
let askAry = askText.split('&')
console.log(askAry) // => ["id=123", "name=hello", "sex=1"]
let result = {}
askAry.forEach(item =>{
let keyValue = item.split('=')
result[keyValue[0]] = keyValue[1]
})
result["hash"] = wellText
console.log(result) // =>{id: "123", name: "hello", sex: "1", hash: "box"}
/*
queryURLParams: 获取URL地址中问号传参的信息和哈希值
@params: url[string] 要解析的URL字符串
@return [object]包含参数和哈希值的对象
*/
function queryURLParams(url){
let askIndex = url.indexOf('?')
let wellIndex = url.indexOf('#')
let askText = ''
//url.substring(askIndex + 1,wellIndex)
let wellText = ''
//url.substring(wellIndex + 1)
// #不存在
wellIndex === -1 ? wellIndex = url.length : null
//?存在
askIndex >= 0 ? askText = url.substring(askIndex + 1,wellIndex) : null
wellText = url.substring(wellIndex + 1)
// 获取每一部分信息
let result = {}
wellText !== '' ? result['hash'] = wellText : null
if (askText !== '') {
let ary = askText.split('&')
ary.forEach(item => {
let itemAry = item.split('=')
result[itemAry[0]] = itemAry[1]
})
}
return result
}
// 使用正则的方法
function queryURLParamsNew(url){
let result = {}
let reg1 = /([^?=&#]+)=([^?=&#]+)/g
let reg2 = /#([^?=&#]+)/g
url.replace(reg1,(n,x,y) => result[x] = y)
url.replace(reg2,(n,x) => result['hash'] = x)
return result
}
console.log(queryURLParamsNew('http://www?id=123&name=qwer#box'))
网友评论