In actual development, some data needed to be used when exchanging data with the background through get, so we need to obtain useful information in the url. The following encapsulated functions can already parse the url thoroughly and can be used directly:
function parseURL(url) { var a = document.createElement('a'); a.href = url; return { source: url, protocol: a.protocol.replace(':',''), host: a.hostname, port: a.port, query: a.search, params: (function(){ var ret = {}, seg = a.search.replace(/^/?/,'').split('&'), len = seg.length, i = 0, s; //len = 2 alert(a.search) for (;i<len;i++) { if (!seg[i]) { continue; } s = seg[i].split('='); ret[s[0]] = s[1]; } return ret; })(), file: (a.pathname.match(///([^//?#]+)$/i) || [,''])[1], hash: a.hash.replace('#',''), path: a.pathname.replace(/^([^//])/,'/$1'), relative: (a.href.match(/tps?:////[^//]+(.+)/) || [,''])[1], segments: a.pathname.replace(/^///,'').split('/') }; }The usage of this function is as follows:
var myURL = parseURL(window.location.href); //Parse the url of the current page through the parseURL function; window.location.href can be replaced with any url to be parsed. If you write other urls directly, the format should be strings; var search_obj = myURL.params; //This parsing method is to parse the content of search into an object to facilitate data calls; other methods can be tried by yourself; var url_post = myURL.post; //The port number of the current page;
The above is the brief discussion on the full content of the url parsing function encapsulation of js. I hope everyone supports Wulin.com~