sisterAn / JavaScript-Algorithms

基础理论+JS框架应用+实践,从0到1构建整个前端算法体系
5.51k stars 634 forks source link

阿里编程题:实现一个方法,拆解URL参数中queryString #64

Open sisterAn opened 4 years ago

sisterAn commented 4 years ago

入参格式参考:

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 commented 4 years ago
const queryString = (str)=>{
    const obj = {}
    str.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (obj[k] = v))
    return obj
}
JerryWen1994 commented 4 years ago
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 commented 4 years ago
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 commented 4 years ago
const parse = (url) => {
    const l = new URL(url).searchParams;
    const _params = {};
    l.forEach((v,k) => _params[k] = v);
    return _params
} 
GitYms commented 4 years ago

思路

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

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 commented 4 years ago
const parse = (url) => {
    const l = new URL(url).searchParams;
    const _params = {};
    l.forEach((k,v) => _params[k] = v);
   return _params
} 

key 和 val 貌似反了~ @7777sea

7777sea commented 4 years ago
const parse = (url) => {
    const l = new URL(url).searchParams;
    const _params = {};
    l.forEach((k,v) => _params[k] = v);
   return _params
} 

key 和 val 貌似反了~ @7777sea

已经修改~

guopeng1129972 commented 4 years ago

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 commented 3 years ago
const queryString = (url) =>
  [...new URL(url).searchParams].reduce((acc, cur) => {
    acc[cur[0]] = cur[1];
    return acc;
  }, {});
xllpiupiu commented 3 years ago
/**
 * 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 commented 2 years ago
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 commented 2 years ago
const getUrlQurey = () => location.search
  .slice(1)
  .split('&')
  .reduce((obj, str) => 
          (([k, v]) => ({...obj, [k]: v }) )(str.split('=')), 
          {})