下面将介绍怎样使用JS去解析URL中查询参数信息。
/** * 获取URL查询变量 */ function getQueryVariable(variable, search) { var query = (search || window.location.search).substring(1); var vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if(pair[0] == variable){ return pair[1]; } } return undefined; } // URL信息 // https://localhost:8080/hello?name=helen&age=28&job=java var search = "?name=helen&age=28&job=java"; console.log("name = " + getQueryVariable("name", search)); console.log("age = " + getQueryVariable("age", search)); console.log("job = " + getQueryVariable("job", search));
方式二:
/** * 解析 url 参数 */ var paramObj = (function parseParams() { var re = /([^&=]+)=?([^&]*)/g, decodeRE = /\+/g, decode = function (str) { return decodeURIComponent(str.replace(decodeRE, " ")); }; var search = "?name=helen&age=28&job=java"; var params = {}, e; while (e = re.exec(search.substring(1))) { params[decode(e[1])] = decode(e[2]); } return params; })(); // URL信息 // https://localhost:8080/hello?name=helen&age=28&job=java console.log(paramObj);
/** * 解析 url 参数 */ (function($) { var re = /([^&=]+)=?([^&]*)/g, decodeRE = /\+/g, decode = function (str) { return decodeURIComponent(str.replace(decodeRE, " ")); }; $.parseParams = function(query) { var params = {}, e; while (e = re.exec(query)) { params[decode(e[1])] = decode(e[2]); } return params; }; })(jQuery); // URL信息 // https://localhost:8080/hello?name=helen&age=28&job=java var search = "?name=helen&age=28&job=java"; param = $.parseParams(search.substring(1)); // 解析问号后的 url 参数 console.log(param);