美文网首页
用 split() 的方法获取当前页面URL中的参数

用 split() 的方法获取当前页面URL中的参数

作者: 郭先生_515 | 来源:发表于2019-02-22 17:31 被阅读0次

题目:写一段 JS 程序提取 URL 中使用 GET 方法请求的各个参数( ( 参数名和参数个数不确定) ) ,并将其
返回成一个 json 格式的对象。
例如:

let url = 'http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e';
// 输出结果:{ a: '1', b: '2', c: '', d: 'xxx', 'e': undefined }

代码如下:

let url = 'http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e '

function parseUrl(url) {
    let result = {};
    let arr = url.split('?')[1];
    let arr1 = arr.split('&');
    let len = arr1.length
    for (let i = 0; i < len; i++) {
        let res = arr1[i].split('=');
        result[res[0]] = res[1];
    }
    console.log('result =',result);
}
parseUrl(url);

相关文章

网友评论

      本文标题:用 split() 的方法获取当前页面URL中的参数

      本文链接:https://www.haomeiwen.com/subject/dpoeyqtx.html