首页 > 试题广场 >

标题:解析URL 题目描述:请实现一个函数 parseUrl

[问答题]
标题:解析URL
题目描述:请实现一个函数 parseUrl,将一段字符串解析为object。
url:http://www.xiyanghui.com/product/list?id=123456&sort=discount#title
使用new URL创造一个url对象,可以直接解析出来想要的数据,不需要的可以直接自由过滤
function parseUrl(url){
    const nUrl = new URL(url);
    const obj = {};
    for(let prop in nUrl){
        if(prop != href || prop !== origin){
            obj.prop = nUrl.prop;
        }
    }
    return obj;
}

发表于 2020-04-07 23:20:34 回复(0)
// split把每一项分割成二元组,fromEntries将二元组转化为对象,很适合本题

function parseUrl(url) {
  const params = url.split("?");
  const keyValues = params[1].split("&");
  const arr = keyValues.map(item => {
    return item.split("=");
  });
  const result = Object.fromEntries(arr);       

  return result;
}


编辑于 2020-07-19 14:04:12 回复(0)
function parseUrl(url) {
    let urlObj = {};
    url = url.substr(url.indexOf('?')).split('&');
    url.forEach(item => {
        urlObj[item.split('=')[0]] = item.split('=')[1]
    });
    return urlObj;
}
发表于 2020-01-16 16:27:07 回复(0)
funtion parseUrl (url) {
    let arr = {}
        let urllist = url.split('?')
        let urlitem = urllist[1]
    let arrlist = urlitem.split('&')
    for(let [index, arrlist] of urlitem.entries()) {
        let arritem = arrlist.split('=')
        arr[arritem[0]] = arr[arritem[1]]
    }
    return arr;
}
var urls = 'http://www.xiyanghui.com/product/list?id=12345678&sort=discount#title'
console.log(parseUrl(urls)) 

编辑于 2020-01-07 16:12:48 回复(0)
let _url = 'http://www.xiyanghui.com/product/list?id=123456&sort=discount#title'

let _tempArray1 = _url.split('?')
let _path = _tempArray1[0]
let _hashPosition = _url.search('#')
let _queryArray = _tempArray1[1].split('&')
let _queryMapper = _queryArray.reduce((total, current) => {
  let _arr = current.split('=')
  let _position = _arr[1].search('#')
  total[_arr[0]] = -1===_position? _arr[1]: _arr[1].slice(0, _position)
  return total
}, {})

let _hash = _url.slice(_hashPosition + 1)

let _result = {
  path: _path,
  query: _queryMapper,
  hash: _hash
}

console.log('_____RESULT', _result)

发表于 2019-12-08 06:13:21 回复(0)