如何获取queryUrlParameters

实现一个方法queryURLParameter获取一个URL地址问号后面传递的参数信息

方法一

let url = 'http://www.nylg.cn/index.html?1x=1&name=nylg#box';
/*
 *结果: {
 *   1x:1;
 *   name:'nylg';
 *   HASH:'box';
 * }
 */
//1.获取问号后面的值
let askIndex = url.indexOf('?'),
    wellIndex = url.indexOf('#');
let askText = url.substring(askIndex + 1, wellIndex);
let wellText = url.substring(wellIndex + 1);
console.log(askText,wellText);//=>1x=1&name=nylg box
//2.问号后面值的详细处理
let result = {};
let askAry = askText.split('&');//=>["1x=1","name=nylg"]
askAry.forEach(item => {
    //item:当前从数组中循环的这一项
    let n = item.split('=');
    let key = n[0];
    let value = n[1];
    result[key] = value;
});
//=>{"1x=1","name=nylg"}
result['HASH'] = wellText;
console.log(result);//=>["1x=1","name=nylg","HASH=box"]

方法二

/*queryURLParams:获取URL地址中问号传参的信息和哈希值
 * @params
 *    url [string] 要解析的URL字符串
 * @return
 *    [object] 包含参数和哈希值信息的对象
 */

function queryURLParams(url) {
    //获取?和#后面的信息
    let askIn = url.indexOf('?'),
        wellIn = url.indexOf('#'),
        askText = '',
        wellText = '';
    // #不存在
    wellIn === -1 ? wellIn = url.length : null;
    /*  
    if(askIn>=0){
         // ?存在
         askText=url.substring(askIn+1,wellIn);
     }*/
    // ?存在
    askIn >= 0 ? askText = url.substring(askIn + 1, wellIn) : null;
    wellText = url.substring(wellIn + 1);

    //2.获取每一部分信息
    let result = {};
    wellText !== '' ? result['HASH'] = wellText : null;
    if (askText !== '') {
        let ary = askText.split('&');
        ary.forEach(item => {
            let itemAry = item.split('=');
            result[itemAry[0]] = itemAry[1];
        });
    }
    return result;
}
let url = 'http://www.nylg.cn/index.html?1x=1&name=nylg#box';
let paramsObj = queryURLParams(url);
console.log(paramsObj);

方法三,基于正则封装

function queryURLParams(url) {

    let result = {},
        reg1 = /([^?=&#]+)=([^?=&#]+)/g,
        reg2 = /#([^?=&#]+)/g;
    url.replace(reg1, (n, x, y) => result[x] = y);
    url.replace(reg2, (n, x) => result['HASH'] = x);

    return result;
}
let url = 'http://www.nylg.cn/index.html?1x=1&name=nylg#box';
let paramsObj = queryURLParams(url);
console.log(paramsObj);

你可能感兴趣的:(js)