#35 queryString 分析器


  • 0

    @nikaple
    如果是浏览器端的话
    可以

    var a =  document.createElement('a');
    a.href = url;
    var s = a.search.replace(/^\?/, '')
    

  • -1

    function parseQueryString(url) {
    url = url || window.location.href;
    var objRequest = new Object();
    if(url.indexOf("?") != -1) {
    url = url.split("?")[1];
    var strArr = url.split("&");
    for(var i = 0; i < strArr.length; i++) {
    objRequest[strArr[i].split("=")[0]] = strArr[i].split("=")[1]?decodeURI(strArr[i].split("=")[1]):null;
    }
    }
    return objRequest;
    }


  • 0

    function parseQueryString (url) {
    var a = document.createElement('a')
    a.setAttribute('href', url)
    var search = a.search
    var query = {}
    var kvs = search.replace(/^\?/, '').split(/&/g)
    kvs.forEach(function (kv) {
    kv = kv.split('=')
    if (!kv[0]) return
    if (kv.length === 2) {
    query[kv[0]] = kv[1]
    } else if (kv.length > 2) {
    query[kv[0]] = kv.slice(1).join('=')
    } else {
    query[kv[0]] = null
    }
    })
    return query
    }


  • 0

    var returnVal = {}
    var newArr = []
    var newArr1 = []
    var newArr2 = []

    const parseQueryString = url => {
    if (url.indexOf('#')) {
    url = url.split('#')[0]
    } else {
    url = url
    }
    if (url.indexOf('?') !== -1) {
    var index = url.indexOf('?')
    var newstr = url.substr(index + 1)
    if (newstr.indexOf('&')) {
    newArr = newstr.split('&')
    }
    newArr.map(arr => {
    if (arr.indexOf('#')) {
    newArr2.push(arr.split('#'))
    }
    })

    newArr2.map(arr => {
      if (arr.length > 1) {
        arr = arr.splice(1)
      }
      return arr
    })
    
    newArr2.map(arr => {
      newArr1.push(arr[0].split('='))
    })
    
    newArr1.map(arr => {
      if (arr.length) {
        if (arr.length === 1) {
          arr.push(null)
        }
      }
    })
    newArr1.map(arr => {
      var key = arr[0]
      returnVal[key] = arr[1]
    })
    

    }
    return returnVal
    }

    这个程序控制台结果正确 验证报错“处理 https://scriptoj.com/problems/#?offset=10&limit=100 的结果不正确”


  • 0

    0_1516696924377_upload-1ceaff16-9047-4f2f-a35f-43c203054b5c
    垃圾编译引擎。

    const parseQueryString = (str) => {
    	if (!str)  throw new Error('请传入字符串');
    	if (typeof str !== 'string') throw new TypeError('只接受string类型');
    	if (str.indexOf('?') < 0) return Object.create(null);
    
    	let querys = str.match(/\?.*/g)[0].replace(/\?/g, '').split('&');
    	let obj = {};
    
    	for (let i=0; i<querys.length; i++) {
    		let [key, value = null] = querys[i].split('=');
    		if (key.indexOf('#') > -1) {
    			key = key.split('#')[0];
    		}
    		if (value !== null) {
    			if (value.indexOf('#') > -1) {
    				value = value.split('#')[0];
    			}
    			if (!isNaN(value)) {
    				value = Number.parseInt(value);
    			}
    		}
    		obj[key] = value;	
    	}
    	return obj;
    }
    
    

    求测。。


  • 0

    @administrators

    function parseQueryString(str) {
        const reg = /\?([^?]*)/;
        try {
            const query = reg.exec(str)[1];
            const arr = query.split('&');
            const regSplit = /([^#]+?)=(.*)/;
            const res = {};
            arr.forEach(item => {
                if (item.indexOf('=') === -1) {
                    res[item] = null;
                } else {
                    const arrSplit = regSplit.exec(item);
                    res[arrSplit[1]] = arrSplit[2];
                }
            });
            return res;
        } catch(e) {
            return {};
        }
    }
    

    ** 求解为何不通过? **


  • 0

    const parseQueryString = function(url) {
    	var obj = {};
    	if(url) {
    	  url = url.replace(/#[^#]*$/, "");
    		var index = url.indexOf("?");
    		if(index != -1) {
    			var queryStr = url.substr(index + 1);
    			var marchResult = null;
    			var regex = /(\w+)(=([^&#]+)?)?/g;
    			while((marchResult = regex.exec(queryStr)) != null) {
    				if(marchResult[1] in obj) {
    					var values = obj[marchResult[1]];
    					if(values instanceof Array) {
    						values.push(marchResult[2] ? (marchResult[3]?marchResult[3]:"") : null);
    						obj.marchResult[1] = values;
    					} else {
    						var arr = [];
    						arr.push(values);
    						arr.push(marchResult[2] ? (marchResult[3]?marchResult[3]:"") : null);
    						obj[marchResult[1]] = arr;
    					}
    				} else {
    					obj[marchResult[1]] = marchResult[2] ? (marchResult[3]?marchResult[3]:"") : null;
    				}
    			}
    		}
    	}
    	return obj;
    }
    

  • 0

    function parseQueryString(url) {
      const hash = url.match(/#.*/) || []
      const nonHashUrl = url.replace(hash[0], '')
      let search = nonHashUrl.match(/\?.*/g) || []
    
      if (search.length > 0) {
        search = search.reduce((accumulate, item) => {
          return accumulate.concat(item.replace('?', '').split('&'))
        }, [])
    
        return search.reduce((accumulate, param, index) => {
          const data = param.split('=')
          const key = data.shift()
          const value = data[0] === undefined ? null : data.join('=')
    
          accumulate[key] = value
    
          return accumulate
        }, {})
      } else {
        return {}
      }
    }
    

  • 0

    @147dmy {offset: "10", limit: "100", tag: "all?name=lucy"}


  • 0

    0_1520316208783_upload-ef3f5a88-935f-4b7a-b48f-514b52f19783

    const parseQueryString = (url) => {
          if (url.indexOf('?') === -1) {
            // 没有参数
            return {};
          } else {
            // 有参数 判断参数是否是 hash
            // #?offset=10&limit=100    ?offset=10&limit=100#list
            let urlArr = url.split(/[\?#]/g)[1] ? url.split(/[\?#]/g)[1] : url.split(/[\?#]/g)[2];
            return urlArr.split(/&/g).reduce((a, b) => {
              if (b.indexOf('=') !== -1) {
                let arr = b.split('=');
                a[arr[0]] = arr[1];
              } else {
                a[b] = null;
              }
              return a;
            }, {})
          }
        };
    

    控制台里输出的是对的啊,求解为何不通过?


  • 0

    const parseQueryString = function(url)/* TODO */
    {
      let obj = {};
      if(url.indexOf("?") === -1 || (url.indexOf("#") !== -1 && url.indexOf("#") < url.indexOf("?"))){
        return obj
      }
      let subUrl = url;
      if(url.indexOf("#",url.indexOf("?")) !== -1){
        subUrl = url.substring(0,url.indexOf("#"));
      }
      let search = subUrl.substring(subUrl.indexOf("?")+1,subUrl.length)
      let tempArr = search.split("&");
      tempArr.forEach(item=>{
        let key;
        let val;
        if(item.indexOf("=") === -1){
          key = item;
          val = null;
        }else{
          key = item.substring(0,item.indexOf("="));
          val = item.substring(item.indexOf("=")+1,item.length)
        }
        obj[key] = val
      })
      return obj
    }
    

    我可能是写的最长的那个人,捂脸~~


  • 0

    const parseQueryString = (url) => {
      const search = (url.replace((url.match(/#.*/) || [])[0], '').match(/\?.*/) || [])[0] || "";
      return (search.match(/[^\?&]([^&]+)|[^?&=]+(=([^&]*))/g) || []).reduce((pre, cur) => (pre[cur.slice(0, cur.indexOf('=')>>>0)] = cur.indexOf('=') !== -1 ? cur.slice((cur.indexOf('=') >>> 0) + 1) : null, pre), {})
    }
    
    

  • 0

    暴力法我x

    const parseQueryString = (url) => {
      let reg = /\?.*/,
          obj = {},
          ary = [],
          result;
      index =  url.indexOf('#') > -1 ? url.indexOf('#') : url.length;
      url = url.slice(0, index);
      result = reg.exec(url);
      if (!result) return {};
      url =  "&" + result[0].slice(1);
    
      reg = /[&](\w+)(=[^#&]*)?/g;
      result = reg.exec(url);
      if (!result) return obj;
      while(result){
        ary.push(result);
        result = reg.exec(url);
      }
    
      ary.forEach((item, index) => {
        let key = item[1];
        let value = "";
        if (item[2]) value = item[2].slice(1);
        else {
          if (item[2] === undefined) {
            value = null;
          } else {
            value = "";
          }
        }
        obj[key] = value;
      })
      return obj;
    }
    

  • 0

    const parseQueryString = function(url){
    /* TODO */
    let paramsStr = url.split('?')[1];
    let paramsArr = paramsStr ? paramsStr.split(/[^=\w]/) : [];
    let oObj = {};
    paramsArr.forEach(item => {
    if(item){
    let tmpArr = item.split('=');
    oObj[tmpArr[0]] = tmpArr[1]!==undefined ? tmpArr[1] : null;
    }

    });
    return oObj;
    }

    提示 处理 https://scriptoj.com/problems/?offset=&limit=100#name=jerry 的结果不正确 的错误

    在控制台测试好像没问题啊
    0_1542598084667_upload-19c1af4f-bbd2-42c5-ba94-9435f75435ed

    @ScriptOJ


  • 0

    为什么没有人用浏览器的 URLSearchParams 呢


  • 0

    实在不会用正则取search串,所以用截取字符串形式,期待大佬公布个更优雅的方式

    const parseQueryString = str => str.indexOf('?') > -1 && str.indexOf('#') < 0 || str.indexOf('?') < str.indexOf('#') ? str.substring(str.indexOf('?') + 1, str.lastIndexOf('#') > 0 ? str.lastIndexOf('#') : str.length).split('&').reduce((obj, c) => Object.assign(obj, { [/([^=]+)(=?)(.*)/g.exec(c)[1]]: (/([^=]+)(=?)(.*)/g.exec(c)[2] ? /([^=]+)(=?)(.*)/g.exec(c)[3] : null) }), {}) : {}
    

  • 0

    const parseQueryString = (url) => {
    let result = {};
    if(url.indexOf('#')< url.indexOf('?')){
    url.replace(/(?:?)(\w+=?\d*(&\w+=?\S*))/, (a,b) => {
    let data = b;
    data.split('&').map( (item) => {
    item.replace(/(\w
    )(=?)(\S*)/, ($1 ,$2, $3, $4) => {
    result[$2] = $3 ? $4 : null;
    })
    })
    })
    }
    return result;
    }
    哈希后面应该返回什么呀


  • 0

    const parseQueryString = url => {
      const index1 = url.indexOf('?');
      const index2 = url.indexOf('#');
      
      // 处理的情况1:没有查询参数
      // 处理的情况2:如果#在?前面,#后面认为都是hash,而非查询参数
      if (index1 === -1 || (index1 > index2 && index2 !== -1)) {
        return {}
      }
      // 处理的情况3:如果没有#参数,直接取?后面的字符串
      // 处理的情况4:如果#在?后面,取?和#之间的字符串
      let str = (index2 === -1) ? url.slice(index1 + 1) : url.slice(index1 + 1, index2);
      
      return str.split('&').reduce((total, current) => {
        // 处理的情况5:?name&age=12返回{ name: null, age: '12' }
        if (current.indexOf('=') === -1) {
          total[current] = null;
        } else {
          // 处理的情况6 value中有多个=的情况
          const index = current.indexOf('=');
          const key = current.slice(0, index);
          const value = current.slice(index+1);
          // 处理的情况7 ?name=&age=12 则返回 { name: '', age: '12' }
          total[key] = value || '';
        }
        return total;
      }, {});
    };
    

  • 0

    @ScriptOJ
    我这个有什么问题么?

    const parseQueryString = (str) => {
    let arr1, arr2, arr3
    let obj = {}
    if (str.indexOf('?') !== -1) {
    arr1 = str.split('?')
    if (arr1.length > 0) {
    arr2 = arr1[1].split(/[&#]/)
    for (let i = 0; i < arr2.length; i++) {
    arr3 = arr2[i].split('=')
    if (arr3[1] === undefined) {
    arr3[1] = null
    }
    obj[arr3[0]] = arr3[1]
    }
    }
    }
    return obj
    }/* TODO */


  • 0

    const parseQueryString = function (str) {
    let search = str.match(/?.+$/);
    if (search) {
    search = search[0];
    } else {
    return {};
    }
    let queries = search.replace(/^?/, '').split(/&/g);
    let res = {};
    for(let each of queries) {
    let key = each.match(/(.+?)=/);
    let value = each.match(/=(.*)?/);
    if (key && !(key[1] in res)) {
    if (value) {
    res[key[1]] = value[1] === undefined ? '' : value[1]
    }
    } else {
    res[each] = null;
    }
    }
    return res;
    }
    你好 跑这个例子的时候不让通过,看了答案发现结果是一样的
    https://scriptoj.com/problems/?offset=&limit=100#name=jerry”


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待