This topic appeared in a number of companies in the interview, of course, is too typical, the solution is nothing more than Chaizi or with regular matching to solve, I personally strongly recommend to use regular matching, because the URL allows users to enter at will, if the use of Chaizi characters, there is no fault-tolerant, Will cause the whole JS error. And the regular does not have this problem, he only matched the correct pairing, illegal all filtered out, simple, convenient.
Implementation code:
1. Manual parsing
function Getquerystringargs (URL) {URL= URL = =NULL?Window.location.href:url; varQS = url.substring (Url.lastindexof ("?") +1); varargs = {}; varItems = qs.length >0? Qs.split ('&') : []; varitem =NULL; varName =NULL; varValue =NULL; for(varI=0; i<items.length; i++) {Item= Items[i].split ("="); //use decodeURIComponent () to decode name and value separately (because the query string should be encoded). Name = decodeURIComponent (item[0]); Value= decodeURIComponent (item[1]); if(name.length) {Args[name]=value; } } returnargs;} Console.log (Getquerystringargs ('https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=12306%E7%81%AB%E8%BD%A6%E7%A5%A8%E7%BD%91 %e4%b8%8a%e8%ae%a2%e7%a5%a8%e5%ae%98%e7%bd%91'));//Object {tn: "MONLINE_3_DG", ie: "Utf-8", WD: "12306 train tickets online booking official website"}
2, the use of regular
function Getqueryobject (URL) {URL= URL = =NULL?Window.location.href:url; varSearch = url.substring (Url.lastindexof ("?") +1); varobj = {}; varreg =/([^?&=]+) = ([^?&=]*)/G; //[^?&=]+ says: except? , &, = one or more characters away from//[^?&=]* says: except? , &, = 0 to more characters (any number)Search.replace (Reg, Function (RS, $1, $2) { varName = decodeURIComponent ($1); varval = decodeuricomponent ($2); Val=String (Val); Obj[name]=Val; returnrs; }); returnobj;} Console.log (Getqueryobject ('https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=12306%E7%81%AB%E8%BD%A6%E7%A5%A8%E7%BD%91% e4%b8%8a%e8%ae%a2%e7%a5%a8%e5%ae%98%e7%bd%91'));//Object {tn: "MONLINE_3_DG", ie: "Utf-8", WD: "12306 train tickets online booking official website"}
Resolves query parameters of a URL to a Dictionary object