js解析url参数的方法

作者: 全栈弄潮儿 | 来源:发表于2019-11-20 14:41 被阅读0次

    1、循环

    function getQuery() {
        const url = decodeURI(location.search); // 获取url中"?"符后的字串(包括问号)
        let query = {};
        if (url.indexOf("?") != -1) {
            const str = url.substr(1);
            const pairs = str.split("&");
            for(let i = 0; i < pairs.length; i ++) {
                 const pair = pairs[i].split("=");
                query[pair[0]] = pair[1];
            }
        }
        return query ;  // 返回对象
    }
    
    function getQueryVariable(name) {
        const url = decodeURI(location.search); // 获取url中"?"符后的字串(包括问号)
        let query = {};
        if (url.indexOf("?") != -1) {
            const str = url.substr(1);
            const pairs = str.split("&");
            for(let i = 0; i < pairs.length; i ++) {
                 const pair = pairs[i].split("=");
                 if(pair[0] === name) return  pair[1]; // 返回 参数值
            }
        }
       return(false);
    }
    

    2、正则表达式

    function  getQueryVariable(name) {
          const reg = new RegExp("(^|&)" + name+ "=([^&]*)(&|$)", "i");
          const result = window.location.search.substr(1).match(reg);
          if ( result != null ){
             return decodeURI(result[2]);
         }else{
             return null;
         }
    }
    

    经典前端面试题每日更新,欢迎参与讨论,地址:https://github.com/daily-interview/fe-interview


    更多angular1/2/4/5、ionic1/2/3、react、vue、微信小程序、nodejs等技术文章、视频教程和开源项目,请关注微信公众号——全栈弄潮儿

    微信公众号

    相关文章

      网友评论

        本文标题:js解析url参数的方法

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