#35 queryString 分析器


  • 0

    const parseQueryString = (url) => {
      const search = new URL(url).search.substring(1);
      if(!search) return {};
      return search.split("&").reduce((total, value) => {
        const [key, ...values] = value.split("=")
        if (values.length === 0) {
          total[key] = null
        } else {
          total[key] = values.join("=")
        }
        return total
      }, {})
    }

  • 0

    终于通过了,这里的坑太多了,不对比URI.js执行结果,还真不好整,写的有点多...
    let parseQueryString = url => {
    	const delIndex = url.indexOf('#') < 0 ? url.length : url.indexOf('#');
    	url = url.slice(0, delIndex)
    	console.log(url)
    	const index = url.indexOf('?')
    	if (index < 0) return {}
    	let queryArr = url.slice(index + 1).split('&')
    	queryArr = queryArr.map(item => {
    		const arr = []
    		const i = item.indexOf('=')
    		const n = i < 0 ? item.length : item.indexOf('=')
    		arr[0] = item.slice(0, n)
    		arr[1] = i < 0 ? null : item.slice(n + 1, item.length)
    		return arr
    	})
    	const query = {}
    	queryArr.forEach(item => {
    		if (item.length === 1) {
    			query[item] = null
    		} else {
    			query[item[0]] = item[1]
    		}
    	})
    	return query
    }
    

  • 0

    0_1558514215802_upload-39b76c39-d841-42f0-9ba2-1ec42425c821 针对带两个问号的正确执行结果应该是什么?
    预测结果一:{offset: "10", limit: "100", tag: "all?name"}
    预测结果二:{all: "name"}
    以上两种都不对。


登录后回复
 

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