Skip to content

Instantly share code, notes, and snippets.

const clearCookies = () =>
document.cookie
.split(";")
.forEach(
(c) =>
(document.cookie = c
.replace(/^ +/, "")
.replace(/=.*/, "=;expires=Thu, 01 Jan 1970 00:00:00 UTC"))
);
const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth" });
// Usage
scrollToTop(document.querySelector("#element"));
const validateEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
// Usage
validateEmail("[email protected]"); // true
const validateObject = (object, rules) =>
Object.keys(rules).every((key) => rules[key](object[key]));
// Usage
const rules = {
name: (name) => name.length > 0,
email: (email) => validateEmail(email),
password: (password) => password.length > 0,
};
const rgbToHex = (r, g, b) =>
"#" + ((r << 16) + (g << 8) + b).toString(16).padStart(6, "0");
// Usage
rgbToHex(255, 0, 0); // #ff0000
formatFn("string") + formatFn("string");
const f = (...args) => String.raw(...args); // This returns a normal string
formatFn(f`string` + f`string`);
const compareObjects = (obj1, obj2) => {
const c = Object.keys(obj1),
n = Object.keys(obj2);
return c.length === n.length && c.every((c) => obj1[c] === obj2[c]);
};
// Usage
compareObjects({ a: 1, b: 2 }, { a: 1, b: 2 }); // true
const getSelectedText = () => window.getSelection().toString();
// Usage
getSelectedText(); // Selected text
const getQueryParams = (url) => new URLSearchParams(url.split("?")[1]);
// Usage
getQueryParams("https://example.com?a=1&b=2"); // { a: "1", b: "2" }
const copyToClipboard = (text) =>
navigator?.clipboard?.writeText(text) ?? false;
// Usage
copyToClipboard("Hello World!");