1. Force download file
Tải file với thẻ a. Không hoạt động nếu file được trả về không có header "Content-Disposition: attachment"
const forceDownloadFile = (url) => {
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = url;
anchor.style.display = 'none';
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
};
2. Sao chép văn bản
Copy bất kì văn bản nào vào bàn phím, hỗ trợ cả IE11.
const copyToClipboard = (text) => {
try {
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text);
} else {
let textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((res, rej) => {
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
}
} catch (error) {
console.error(error);
}
};
3. Sao chép ảnh
Chỉ hỗ trợ ảnh với mime type là "image/png"
4. Tính khoảng thời gian đã qua
5. CSS hex color ngẫu nhiên
const randomColor = () =>
`#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
6. Định dạng số
7. Thay thế tất cả các ký tự trong chuỗi
let str = 'ababaa';
// Replace "b" with ""
// Output "aaaa"
// Regex
str.replace(/b/g, '');
// Better regex
str.replace(new RegExp('b', 'g'), '');
// Split and join
str.split('b').join('');
// Replace All (modern browser)
str.replaceAll('b', '');
// While loop
while (str.includes('b')) str = str.replace('b', '');
8. Flatten deep array
// Dùng đệ quy
const flatten = (arr) =>
arr.reduce(
(acc, current) =>
acc.concat(Array.isArray(current) ? flatten(current) : current),
[],
);
// Dùng Array.flat (không support IE)
const flatten = (arr) => arr.flat(Infinity);
9. Format video time
10. Format file size
Kết luận
Và đó là 10 code snippets, utility functions rất hữu ích mà bạn có thể áp dụng vào project của mình.
top