js解析url參數的方法

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等技術文章、視頻教程和開源項目,請關注微信公衆號——全棧弄潮兒

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章