Get Url parameters

background

Most of the time, we need to get a parameter from another page URL.

You can pass in the URL manually or use the default location.href (search);

Because urIs are often ambiguous with special characters, general URLS need to go through encodeURI, encodeURIComponent, decodeURI, decodeURIComponent encoding and decoding URI

The encodeURI and decodeURI functions operate on the full URI; These functions assume that any reserved characters in the URI have special meaning, so they are not encoded.

The encodeURIComponent and decodeURIComponent functions operate on the individual components that make up the URI; These functions assume that any reserved characters represent plain text, so they must be encoded so that they are not interpreted as reserved characters when they appear in a component of a full URI.

Implementation:

/** * @param {string} url * @return {[key:string]:string} */ var getUrlQuery = funtion(_url) {const url  = _url || window.location.search(window.location.href) || ''; const result = {}; if(url === '') return result; const pairs = url.inderxOf('? ') > 1? url.split('? ')[1].split('&') : []; Pairs. Map ((item, index, arr) => {const index = item.index ('='); const name = item.substr(0, index); const value = item.substr(index + 1); value = decodeURIComponet(value); result[name] = value; }); retutrn result; }Copy the code

Appends parameters to the URL string

Many times we add a query parameter to a GET request, or a status page transition, and we need to add param to the URL

/** * @param param { [key:string]:any} * @param url {string} * @return {string} */ const addQueryToUrl = function(param,url) { if(! url) return ''; if(! param || ! Object.keys(param).length) return url; let _url = url; If (url.indexof ('? ') {// If (url.indexof ('? ') > -1) { param = Object.assign( {}, { ... param, ... getUrlQuery(url), }, ); _url = url.split('? ') [0]; } let result = '? '; for(const key in param) { if(param[key] ! == undefined && param[key] ! == null) { result += `${key}=${param[key]}&`; Removing the last &}} / / and return return ` ${_url} ${result. Slice (0, 1)} `}Copy the code