《那些比较有用的代码片段》

日期处理

判断一个日期是否有效

1
2
3
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00"); // true

计算两个日期之间的间隔

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

dayDif(new Date("2021-11-3"), new Date("2022-2-1")); // 90

查找日期位于一年中的哪一天

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

dayOfYear(new Date()); // 307

时间格式化

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

timeFromDate(new Date(2021, 11, 2, 12, 30, 0)); // 12:30:00
timeFromDate(new Date()); // 返回当前时间 09:00:00

字符串的处理

字符串首字母大写

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

capitalize("hello world"); // Hello world

随机字符串

1
2
3
const randomString = () => Math.random().toString(36).slice(2);

randomString();

截断字符串

1
2
3
4
const truncateString = (string, length) =>
string.length < length ? string : `${string.slice(0, length - 3)}...`;

truncateString("Hi, I should be truncated because I am too loooong!", 36); // 'Hi, I should be truncated because...'

数组的处理

从数组中移除重复项

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

console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));

判断数组是否为空

1
2
3
const isNotEmpty = (arr) => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]); // true

合并两个数组

1
2
3
const merge = (a, b) => a.concat(b);

const merge = (a, b) => [...a, ...b];

颜色操作

将 RGB 转换成十六进制

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

rgbToHex(255, 255, 255); // '#ffffff'

获取随机十六进制颜色

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

randomHex();

浏览器的操作

获取内容到剪切板

该方法使用 navigator.clipboard.writeText 来实现将文本复制到剪贴板:

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

copyToClipboard("Hello World");
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=/`))
);

获取选中的文本

该方法通过内置的 getSelection 属性获取用户选择的文本:

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

getSelectedText();

检测是否为黑暗模式

1
2
3
4
5
const isDarkMode =
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;

console.log(isDarkMode);

滚动到页面顶部

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

goToTop();

滚动到页面底部

1
2
3
const scrolledToBottom = () =>
document.documentElement.clientHeight + window.scrollY >=
document.documentElement.scrollHeight;

打开浏览器打印框

1
const showPrintDialog = () => window.print();

校验

校验身份

1
2
const validateIDCard = (value) =>
/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);

校验支付宝账号

1
2
3
4
const validateAlipay = (value) =>
/^1\d{10}$|^[a-zA-Z\d._-]*\@[a-zA-Z\d.-]{1,10}\.[a-zA-Z\d]{1,20}$/.test(
value
);

校验银行卡

1
const validateBankCode = (value) => /^\d{13,19}$/.test(value);

校验手机号

1
const validatePhone = (value) => /^1\d{10}$/.test(value);

压缩图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const compressImg = (file) => {
const fileSize = parseFloat(
Number.parseInt(file.size, 10) / 1024 / 1024
).toFixed(2);
const reader = new FileReader();
reader.readAsDataURL(file);
return new Promise((resolve) => {
reader.onload = (e) => {
const img = new Image();
img.src = e.target.result;
img.onload = () => {
const w = img.width;
const h = img.height;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
let base64;
canvas.setAttribute("width", w);
canvas.setAttribute("height", h);
ctx.drawImage(img, 0, 0, w, h);
if (fileSize <= 1) {
base64 = canvas.toDataURL(file.type, 1);
} else if (fileSize <= 3) {
base64 = canvas.toDataURL(file.type, 0.8);
} else if (fileSize <= 5) {
base64 = canvas.toDataURL(file.type, 0.5);
} else {
base64 = canvas.toDataURL(file.type, 0.1);
}
let fileName = file.name;
fileName = fileName.replace(
/^(.+)\.(.+)$/,
(fullName, name, suffix) =>
name +
Math.floor(Math.random() * (9999 - 1000) + 1000) +
"." +
suffix
);
resolve(dataURLtoFile(base64, fileName));
};
};
});
};

将 BASE64 转换文件

1
2
3
4
5
6
7
8
9
10
11
12
const dataURLtoFile = (dataurl, filename) => {
const arr = dataurl.split(",");
const mime = arr[0].match(/:(.*?);/)[1];
if (!filename) filename = `${Date.parse(new Date())}.jpg`;
const bstr = window.atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
};

修改数组对象中的 key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const arr = [
{
id: 1,
name: "Jane",
gender: "male",
},
{
id: 2,
name: "Jhon",
gender: "male",
},
{
id: 3,
name: "Bob",
gender: "male",
},
];

const keyMap = {
id: "learn_id",
};
const modifyObjKeys = (arr, keyMap) => {
arr.forEach((e) => {
for (let key in e) {
let newKey = keyMap[key];
if (newKey) {
e[newKey] = e[key];
delete e[key];
}
}
});
return arr;
};

console.log(modifyObjKeys(arr, keyMap));
// [
// { name: 'Jane', gender: 'male', learn_id: 1 },
// { name: 'Jhon', gender: 'male', learn_id: 2 },
// { name: 'Bob', gender: 'male', learn_id: 3 }
// ]