#35 queryString 分析器


  • 0

    怎么贴代码呢,本地测试通过了,上面提示没通过


  • 0
    administrators

    @marlboro 你可以把代码和出错信息都贴一下。代码用 markdown 语法的 ``` 包裹起来。


  • 0

    处理 https://scriptoj.comproblems/?offset=10&limit=100&tag=all?name=lucy 的结果不正确
    正确的应该是什么


  • 0

    var parseQueryString = (url)=> {
        let uri = url.indexOf('#');
        let index = url.indexOf('?') +1;
        let text = url.slice(index,uri)
        console.log(text)
        let nums = text.split("&");
        const res = {};
        if(nums.length!==1){
            nums.map( (ele) => {
                let part = ele.split("=");
                res[part[0]] = (part[1] == undefined) ? null : part[1]
            })
        }
        return res
    }
    //提交后显示处理 https://scriptoj.com?offset=10&limit=100 的结果不正确
    
    

    胡子大大给看看呗 。在控制台输出正常


  • 0

    哈希应该返回什么呀,哈希#后面的是不返回还是返回的和&后面的一样


  • 0

    用 URL API 会方便很多:

    const parseQueryString = url => {
      const search = new URL(url).search
      if (search === '') {
        return {}
      }
      const kv = search.substr(1).split('&')
      const result = kv.reduce((obj, kv) => {
        const [k, ...v] = kv.split('=')
        obj[k] = v.length === 0 ? null : v.join('=')
        return obj
      }, {})
      return result
    }
    

  • 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


登录后回复
 

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