Skip to content
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

Open
sisterAn opened this issue Jun 14, 2020 · 12 comments
Open

Comments

@sisterAn
Copy link
Owner

sisterAn commented Jun 14, 2020

入参格式参考:

const url = 'http://sample.com/?a=1&b=2&c=xx&d=#hash';

出参格式参考:

const result = { a: '1', b: '2', c: 'xx', d: '' };
// 拆解URL参数中queryString,返回一个 key - value 形式的 object
@xiaopingbuxiao
Copy link

const queryString = (str)=>{
    const obj = {}
    str.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (obj[k] = v))
    return obj
}

@JerryWen1994
Copy link

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))

@Planck-Ho
Copy link

Planck-Ho commented Jun 15, 2020

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 {}
}

@7777sea
Copy link

7777sea commented Jun 15, 2020

const parse = (url) => {
    const l = new URL(url).searchParams;
    const _params = {};
    l.forEach((v,k) => _params[k] = v);
    return _params
} 

@GitYms
Copy link

GitYms commented Jun 15, 2020

思路

字符串分割拿到参数相关的字符串,再做类型转换

code

const dismantle = (url) => {
     const aimUrl = url.split('?').pop().split('#').shift().split('&');
     const res = {};
     aimUrl.forEach(item => {
          const [key, val] = item.split('=');
          res[key] = val;
     });
     return res;
}

@onlyil
Copy link

onlyil commented Jun 15, 2020

const parse = (url) => {
    const l = new URL(url).searchParams;
    const _params = {};
    l.forEach((k,v) => _params[k] = v);
   return _params
} 

key 和 val 貌似反了~ @7777sea

@7777sea
Copy link

7777sea commented Jun 15, 2020

const parse = (url) => {
    const l = new URL(url).searchParams;
    const _params = {};
    l.forEach((k,v) => _params[k] = v);
   return _params
} 

key 和 val 貌似反了~ @7777sea

已经修改~

@guopeng1129972
Copy link

const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';

const queryString = (url) => {
let urlStrList = url.split("/?")[1].split('#')[0].split('&')
let urlData={};
for (let [index, urlStr] of urlStrList.entries()) {
let itemList = urlStr.split('=')
urlData[itemList[0]] = decodeURIComponent(itemList[1])
}
return urlData
}
console.log(queryString(url))

@sisterAn 哈喽,
我有个问题,你那个输出的例子为什么要d: '' ?
&d=2#hash
d不应该是2吗?
还有#hash是啥意思?是因为这个d就要取成空了吗?

@hix41
Copy link

hix41 commented Dec 9, 2020

const queryString = (url) =>
  [...new URL(url).searchParams].reduce((acc, cur) => {
    acc[cur[0]] = cur[1];
    return acc;
  }, {});

@xllpiupiu
Copy link

/**
 * 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))

@sisterAn
Copy link
Owner Author

sisterAn commented Mar 8, 2022

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: ''}

@NoBey
Copy link

NoBey commented Mar 23, 2022

const getUrlQurey = () => location.search
  .slice(1)
  .split('&')
  .reduce((obj, str) => 
          (([k, v]) => ({...obj, [k]: v }) )(str.split('=')), 
          {})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests