背景
很多时候,我们需要获取另外一个页面url传过来的参数。
可以手动传入url 或者使用默认的location.href(search);
由于uri很多时候特殊字符会有歧义,一般的url 需要经过encodeURI、encodeURIComponent、decodeURI、decodeURIComponent编码和解码 URI
encodeURI 和 decodeURI 函数操作的是完整的 URI;这俩函数假定 URI 中的任何保留字符都有特殊意义,所有不会编码它们。
encodeURIComponent 和 decodeURIComponent 函数操作的是组成 URI 的个别组件;这俩函数假定任何保留字符都代表普通文本,所以必须编码它们,所以它们(保留字符)出现在一个完整 URI 的组件里面时不会被解释成保留字符了。
实现:
/**
* @param {string} url
* @return { [key:string]:string}
*/
/** 获取url参数 */
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) => {
// 只查找到第一个"="符号,这样就不会把token中等号也裁剪掉
const index = item.indexOf('=');
const name = item.substr(0, index);
const value = item.substr(index + 1);
value = decodeURIComponet(value);
result[name] = value;
});
retutrn result;
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END