-
Notifications
You must be signed in to change notification settings - Fork 641
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
阿里编程题:实现一个方法,拆解URL参数中queryString #64
Comments
|
function getParams(u: URL) {
const s = new URLSearchParams(u.search)
const obj = {}
s.forEach((v, k) => (obj[k] = v))
return obj
}
const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
getParams(new URL(url)) |
function getQuery (queryStr) {
const [, query] = queryStr.split('?')
if (query) {
return query.split('&').reduce((pre, cur) => {
const [key, val] = cur.split('=')
pre[key] = decodeURIComponent(val)
return pre
}, {})
}
return {}
} |
|
思路字符串分割拿到参数相关的字符串,再做类型转换 code
|
key 和 val 貌似反了~ @7777sea |
已经修改~ |
const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash'; const queryString = (url) => { @sisterAn 哈喽, |
|
/**
* url= url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
*/
//使用URL构造函数 使得url具有searchParams属性
const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
function getUrlParams(url) {
const urlParams = new URL(url)
const params = urlParams.searchParams
console.log('params: ', params);
const obj = {}
//使用forEach map只能循环数组吗???
params.forEach((item,index)=>obj[index] = item)
return obj
}
console.log(getUrlParams(url))
//使用普通的split map循环
function getUrlParams2(url) {
const indexStart = url.indexOf('?')
const indexEnd = url.indexOf('#')
const params = url.slice(indexStart+1,indexEnd)
let obj = {}
params.split('&').map(item=>{
const objParams = item.split('=')
obj[objParams[0]] = objParams[1]
})
return obj
}
console.log(getUrlParams2(url)) |
function queryString(url) {
let res = {}
url.replace(/([^?&]+)=([^&#]*)/g, (_, k, v)=>{
res[k] = v
})
return res
}
var url = 'http://sample.com/?a=1&b=2&c=xx&d=#hash'
console.log(queryString(url))
// {a: '1', b: '2', c: 'xx', d: ''} |
const getUrlQurey = () => location.search
.slice(1)
.split('&')
.reduce((obj, str) =>
(([k, v]) => ({...obj, [k]: v }) )(str.split('=')),
{}) |
入参格式参考:
出参格式参考:
The text was updated successfully, but these errors were encountered: