/

js/ts中常用工具集

1
2
const cookie = (name) =>
`; ${document.cookie}`.split(`; ${name}=`).pop().split(";").shift();

eg:

1
cookie("userInfo");

RGB 转十六进制颜色代码

1
2
const rgbToHex = (r, g, b) =>
"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

eg:

1
rgbToHex(0, 51, 255);

复制文字到剪贴板

1
const copyToClipboard = (text) => navigator.clipboard.writeText(text);

eg:

1
copyToClipboard("Hello World");

查找日期位于一年中的第几天

1
2
const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

eg:

1
dayOfYear(new Date());

英文字符串首字母大写

1
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);

eg:

1
capitalize("follow for more");

计算两个日期之间的天数差

1
2
const dayDif = (date1, date2) =>
Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

eg:

1
dayDif(new Date("2020-10-21"), new Date("2021-10-22"));
1
2
3
4
5
6
7
8
const clearCookies = document.cookie
.split(";")
.forEach(
(cookie) =>
(document.cookie = cookie
.replace(/^ +/, "")
.replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`))
);

eg:

1
clearCookies();

生成随机十六进制颜色代码

1
2
3
4
const randomHex = () =>
`#${Math.floor(Math.random() * 0xffffff)
.toString(16)
.padEnd(6, "0")}`;

数组去重

1
const removeDuplicates = (arr) => [...new Set(arr)];

从 url 获取 query 参数

1
2
3
4
5
6
7
8
9
10
11
const getParameters = (URL) => {
URL = JSON.parse(
'{"' +
decodeURI(URL.split("?")[1])
.replace(/"/g, '"')
.replace(/&/g, '","')
.replace(/=/g, '":"') +
'"}'
);
return JSON.stringify(URL);
};

或者

1
Object.fromEntries(new URLSearchParams(window.location.search));

eg:

1
getParameters(window.location);

获取 Date 对象的时间

1
const timeFromDate = (date) => date.toTimeString().slice(0, 8);

eg:

1
timeFromDate(new Date());

数组求平均值

1
const average = (...args) => args.reduce((a, b) => a + b) / args.length;

eg:

1
average(1, 2, 3, 4);

页面回到顶部

1
const goToTop = () => window.scrollTo(0, 0);

翻转字符串

1
const reverse = str => str.split('').reverse().join('');

获取用户选中的文本

1
const getSelectedText = () => window.getSelection().toString();

打乱数组

1
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

判断是否处于深色模式

1
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

返回 n 天后的日期对象

1
2
3
4
5
export function dateLag(day: Date, lag: number) {
var day1 = day;
day1.setDate(day1.getDate() + lag);
return day1;
}

日期转 YYYY-MM-DD 字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export function formatDate(date: Date) {
return (
"" +
String(date.getFullYear()) +
"-" +
(date.getMonth() < 9
? "0" + String(date.getMonth() + 1)
: String(date.getMonth() + 1) +
"-" +
(date.getDate() < 10
? "0" + String(date.getDate())
: String(date.getDate())))
);
}