eva-engine / 2021questions

12 stars 1 forks source link

2020-03-06 取URL参数 #1

Open fanmingfei opened 4 years ago

fanmingfei commented 4 years ago

今天第一天先来一道简单的

在日常开发中,我们经常会遇到取url上面参数的需求,今天这道题就是取URL上面的参数。

不需要考虑浏览器兼容性

image

SunYiwen commented 4 years ago
function getUrlParams(url){
  let paramsArray = url.split('?')[1].split('&');
  let params = {};
  for(let i=0;i<paramsArray.length;i++){
    let param = paramsArray[i].split('=');
    if(param.length === 2){
      let key = param[0];
      let value = param[1];
      params[key] = value;
    }
    else{
      let key = param[0];
      params[key] = true;
    }
  }
  return params;
}

let params = getUrlParams('http://domain.com?page=10&action=list&lazy');
console.log(params.page);
console.log(params.action);
console.log(params.lazy);
xiaosen7 commented 4 years ago

function getUrlParams(url) {     let [_, query] = url.split('?');     return query ? query.split('&').reduce((memo, str) => {         let [key, value] = str.split('=');         memo[key] = value;         return memo;     }, {}) : {}; }

IskenHuang commented 4 years ago

还有很多场景没处理到,像是 url 本身不合法,parseInt 没办法处理精确数字不合法等

function getUrlParams(url) {
    let result = {}
    let atag = document.createElement('a')
    atag.setAttribute('href', url)
    let queryString = atag.search.slice(1)
    queryString.split('&').map((item) => {
        let ary = item.split('=')
        let key = ary[0]
        let val = ary[1] ? ary.slice(1).join('') : ary[1]
        if (key) {
            if (val === undefined) {
                val = true
            } else {
                let temp = parseInt(val, 10)
                val = temp ? temp : val
            }
        }
        result[key] = val
    })
    return result
} 
joker1148 commented 4 years ago
function getUrlParams(url){
    let arr = url.split("?")[1].split("&")
    let newObj = {}
    arr.forEach(element => {
        let curObj = element.split("=")
        let newCurObj = curObj[1] == undefined ? true : curObj[1]
        newObj[curObj[0]] = newCurObj
    });
    return newObj
}
var url = "http://domain.com?page=10&page=10&action=list&lazy"
var param = getUrlParams(url)
console.log(param.page)
console.log(param.action)
console.log(param.lazy)
fanmingfei commented 4 years ago
function getUrlParams(url) {
    // 复用 @IskenHuang 获取query的方法
    let atag = document.createElement('a')
    atag.setAttribute('href', url)

   const a = new URLSearchParams(atag.search)
   const params = {}
   for (let [key, val] of a.entries()) {
       params[key] = val
   }
   return params
}

atag.search 相关的标准 URLSearchParams

LiZhaji commented 4 years ago
function getUrlParams(url) {
  const params = {};
  url
    .slice(0, url.indexOf("#")) // 去除hash影响
    .split("?").pop().split("&")
    .map(item => decodeURIComponent(item)) // 解码
    .forEach(item => {
      const key = item.split("=");
      params[key[0]] = key[1];
    });
  return params;
}
getUrlParams('http://a.com?a=1&b=%3F2#c=3&d=4')
BrunaDeLafel commented 4 years ago

`var url = 'http://www.inode.club?page=10&action=list&node'; function getUrlParams(url){

var obj = {};
var params = url.split('?')[1];

var objprop = params.split('&');

for(let i = 0;i < objprop.length;i ++){
    if(Array.isArray(objprop[i].split('=')) === true){
        obj[objprop[i].split('=')[0]] = objprop[i].split('=')[1]
    }
    else{
        obj[objprop[i]] = true;
    }
}

return obj;

}

const newobj = getUrlParams(url); console.log(newobj);`

liuyingbin19222 commented 4 years ago
function getUrlParams(url){
    var dic = new Object();
    var url = url.split("?")[1];
    var secondhalf = url.split("&");
    for  (var i in secondhalf){
        dic[secondhalf[i].split("=")[0]] = secondhalf[i].split("=")[1] == undefined  ? true : secondhalf[i].split("=")[1];
    }
    return dic;
}
let params = getUrlParams("http://domian.com?page=10&action=get&lazy")
console.log("page:",params.page)
console.log("lazy:",params.lazy)
FoSuCloud commented 4 years ago
        function getUrlParams(url){
            var arr=url.split('?');
            var obj={}
            if(arr.length>1){
                arr=arr[1].split('&')
                for(var i=0;i<arr.length;i++){
                    var line=arr[i].split('=')
                    // 不存在数值时就返回true
                    obj[line[0]]=line[1]?line[1]:true
                }
                return obj
            }else{
                throw new Error("不存在参数")
            }
        }
        var obj=getUrlParams("http://localhost?name=222&age=1&lazy")
        console.log(obj.name)
        console.log(obj.age)
        console.log(obj.lazy)
wwwx commented 3 years ago
function getUrlParams(url) {
    if (typeof url !== 'string') {
        throw new Error('the type of `url` must be a string.');
    }

    if (url.indexOf('?') > 0) {
        query = url.substr(url.indexOf('?') + 1)
    }

    if (!query) return {};

    var params = {};
    var items = query.split('&');
    var len = items.length;

    while (len-- > 0) {
        var _name = items[len].split('=')[0];
        var value = items[len].split('=')[1] || true;
        params[_name] = value;
    }

    return params;
}

var url = 'http://domain.com?page=10&action=list&lazy';
var params = getUrlParams(url)
console.log(JSON.stringify(params, null, 4))