常用工具类方法总结

from: https://submara.com/posts/utils/

存储localStorage

1
2
3
4
5
6
7
export const setStorage = (name, content) => { 
if (!name) return;
if (content) {
content = JSON.stringify(content);
}
window.localStorage.setItem(name, content);
};

获取localStorage

1
2
3
4
5
6
7
8
9
export const getStorage = name => {
if (!name) return;
const data = window.localStorage.getItem(name);
if (data) {
return JSON.parse(data);
} else {
return null;
}
};

删除localStorage

1
2
3
4
export const removeStorage = name => {
if (!name) return;
window.localStorage.removeItem(name);
};

存储sessionStorage

1
2
3
4
5
6
7
export const setSessionStorage = (name, content) => {
if (!name) return;
if (content) {
content = JSON.stringify(content);
}
window.sessionStorage.setItem(name, content);
};

获取sessionStorage#

1
2
3
4
export const getSessionStorage = name => {
if (!name) return;
return JSON.parse(window.sessionStorage.getItem(name));
};

删除sessionStorage

1
2
3
4
export const removeSessionStorage = name => {
if (!name) return;
window.sessionStorage.removeItem(name);
};

下载文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/** @param {String} path - 下载地址/下载请求地址。
*** @param {String} name - 下载文件的名字(考虑到兼容性问题,最好加上后缀名)*/
export const downloadFile = (path) => {
const xhr = new XMLHttpRequest();
let fileType = path.substring(path.lastIndexOf('/') + 1);
xhr.open('get', path);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = function () {
if (this.status === 200 || this.status === 304) {
const fileReader = new FileReader();
fileReader.readAsDataURL(this.response);
fileReader.onload = function () {
const a = document.createElement('a');
a.style.display = 'none';
a.href = this.result;
a.download = `${fileType}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
}
};
};

文件大小格式化

1
2
3
4
5
6
export const formatFileSize = (bytes, decimalPoint = 2) => {
if (bytes === 0) return '0 Bytes';
const k = 1000;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(decimalPoint)) + ' ' + sizes[i];};

生成随机长度的字符串#

1
2
3
4
5
6
7
8
export const randomString = (len = 20) => {
const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
const strLen = chars.length;
let randomStr = '';
for (let i = 0; i < len; i++) {
randomStr += chars.charAt(Math.floor(Math.random() * strLen));
}
return randomStr;};

解析url地址参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/** @param url* @param key*/
export const getUrlParams = (url, key) => {
if (!url) return;
const params = (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{},);
if (key) {
if (params[key]) {
return params[key];
} else {
return null;
}
} else {
return params;
}
};

复制字符串到剪贴板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected = document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) : false; el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};

格式化时间戳

1
2
3
4
5
6
7
8
9
10
11
12
13
/*** timestamp 当前时间戳,毫秒* format 时间格式(例如:YYYY-MM-DD hh:mm:ss):*/
export const dateFormat = (timestamp, format) => {
if (!timestamp) return; let date = new Date(timestamp);
let o = { "M+": date.getMonth() + 1, //月 "D+": date.getDate(), //天 "W": "日一二三四五六".charAt(date.getDay()), //星期 "h+": date.getHours(), //时 "m+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季节 "S": date.getMilliseconds() //毫秒 };
if (/(Y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); }
for (let k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length === 1 ?
o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;};

格式化时间(源数据单位 s)

1
2
3
4
export const formatDateHms = (date = 0, format = '') => {
const hours = Math.floor(date / 3600).toString().padStart(2, '0');
const minute = Math.floor((date / 60) % 60).toString().padStart(2, '0');
const second = Math.floor(date % 60) .toString() .padStart(2, '0'); if (format === 'cn') { return `${hours}${minute}${second}秒`; } else { return `${hours}:${minute}:${second}`; }};

请我喝杯咖啡吧~

支付宝
微信