前端常用工具方法总结
推荐js工具库:
Lodash(中文):https://www.lodashjs.com/
Lodash(英文):https://lodash.com/
xe-utils:https://x-extends.gitee.io/xe-utils/#/
1.getQueryString 获取url值
/** * @description: 获取地址栏url 值 * @example 地址栏url http://casicloud.com?a=123 * getQueryString(a) ===> 123 * @param {name} **/
function getQueryString(name) { const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)") const r = window.location.search.substr(1).match(reg) if (r != null) { return unescape(r[2]) } return null }
2.getParam 获取url 值
/** * @description: 获取url 值 * @param {url} url * @param {name} key名称 * @example getParam('http://casicloud.com?a=123', 'a') ===> 123 **/ function getParam(url, name) { try { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = url.split('?')[1].match(reg); if (r != null) { return unescape(r[2]) } return '' } catch (e) { return '' } };
3.parseParam 对象转序列化字符串
/** * @description: 对象转序列化字符串 * @param {param} 将要转为URL参数字符串的对象 * @param {key} URL参数字符串的前缀 默认不用传 * @example parseParam({a:1, b:2}) ===> a=1&b=2 **/
function parseParam(param, key) { if (param == null) { return '' }; var paramStr = ''; var type = typeof (param); if (type == 'string' || type == 'number' || type == 'boolean') { paramStr += "&" + key + "=" + encodeURIComponent(param); } else { for (var i in param) { var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i); paramStr += '&' + parseParam(param[i], k); } } return paramStr.substr(1); }