1. The so-called url parameter, that is, the content after the "?" in the address bar
2. Example + Analysis
(1) Get the content after "?" in the address bar
// directly acquired (content after acquisition?) var search = window.location.search; // 例如:"?userName=cyq&age=24&sex=f" // dead address var href = "http://www.cyqzy.com?userName=cyq&age=24&sex=f"; var ksbz = href.indexOf("?"); // Three ways to intercept the string and return the result: userName=cyq&age=24&sex=f var hrefStr = href.substr(ksbz+1); // 参数(start,length) var hrefStr2 = href.substring(ksbz+1); // parameter (start,end), the return result does not include end var hrefStr3 = href.slice(ksbz+1); // parameter (start,end), the return result does not include end
(2) Method 1 (returns a json object)
var splitStr = hrefStr.split("&"); // 返回结果:["userName=cyq", "age=24", "sex=f"] var urlObj = {} // equivalent to var urlObj = new Object() for(var i = 0; i < splitStr.length; i++){ urlObj[splitStr[i].split("=")[0]] = splitStr[i].split("=")[1]; } console.log(urlObj) // 返回结果:Object {userName: "cyq", age: "24", sex: "f"}
(3) Method 2 (get parameter value)
var name = "age"; // name refers to the attribute name to be taken, such as username or age or sex var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var res = hrefStr.match(reg); if (res != null){ console.log(res);//["&age=24&", "&", "24", "&", index: 12, input: "userName=cyq&age=24&sex=f"] console.log(res[2]); // 24 }