jQuery 解析 url 参数

应用场景:

三毛:我现在拿到一个 url 地址(https://www.google.com/search?dcr=0&ei=5C&q=param),我现在要获取 location.search 后的参数,并组成一个对象,{dcr: '0', ej: '5C', q: 'param'},怎么处理?

五毛:呃,稍等,我去谷歌一下

 

谷歌结果:

// 解析 url 参数
(function($) {
    var re = /([^&=]+)=?([^&]*)/g,
        decodeRE = /\+/g,
        decode = function (str) { return decodeURIComponent( str.replace(decodeRE, " ") ); };

    $.parseParams = function(query) {
        let params = {}, e;

        while ( e = re.exec(query) ) params[ decode(e[1]) ] = decode( e[2] );
        return params;
    };
})(jQuery);

 

如何使用:

$.parseParams(location.href.split('?')[1] || '');

 

 

举个栗子:

var url = 'https://www.google.com/search?dcr=0&ei=5C&q=param', // 模拟的 url 地址
    param = $.parseParams(url.split('?')[1] || ''); // 解析问号后的 url 参数
console.log(param); // {dcr: "0", ei: "5C", q: "param"}

 

posted @ 2017-12-26 12:17  lpbottle  阅读(6128)  评论(0编辑  收藏  举报