获取浏览器 Cookie 的值
export const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
将 RGB 转换为十六进制
export const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
复制到剪贴板
export const copyToClipboard = (text) => navigator.clipboard.writeText(text);
检查日期是否有效
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
找出一年中的某一天
export const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
将字符串首字母大写
export const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
计算两天之间相差的天数
export const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
清除所有 Cookie
export const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.\*/, `=;expires=${new Date(0).toUTCString()};path=/`));
生成随机十六进制
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
从 URL 获取查询参数
const getParameters = (URL) => {
URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
return JSON.stringify(URL);
};
求平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
回到顶部
const goToTop = () => window.scrollTo(0, 0);
检查数组是否为空
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
打乱数组
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
检测用户是否处于暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
343123.23 转化为「343,123.23」
function format(number) {
return number && number.replace(/(?!^)(?=(\d{3})+\.)/g, ",");
}
获取文件扩展名
function getFileExtension(filename) {
return filename.slice(((filename.lastIndexOf(".") - 1) >>> 0) + 2);
}