🔥Handy Copy-Paste Javascript Snippets Part 3
Updated: February 20, 2022•3 min read
👉 Part 1 -> 🔥Handy Copy-Paste Javascript Snippets Part 1 👉 Part 2 -> 🔥Handy Copy-Paste Javascript Snippets Part 2
Strings
Check if a path is relative
const isRelative = (path) => !/^([a-z]+:)?[\\/]/i.test(path); // ExamplesisRelative("/foo/bar/baz"); // falseisRelative("C:\\foo\\bar\\baz"); // falseisRelative("foo/bar/baz.txt"); // trueisRelative("foo.md"); // true
Make the first character of a string lowercase
const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;// ExamplelowercaseFirst("Hello World"); // 'hello World'
Repeat a string
const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes);
Check if a string is a hexadecimal color
const isHexColor = (color) =>/^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color); // ExamplesisHexColor("#012"); // trueisHexColor("#A1B2C3"); // trueisHexColor("012"); // falseisHexColor("#GHIJKL"); // false
Dates
Add “am/pm” suffix to an hour
// `h` is an hour number between 0 and 23const suffixAmPm = (h) =>`${h % 12 === 0 ? 12 : h % 12}${h < 12 ? "am" : "pm"}`; // ExamplessuffixAmPm(0); // '12am'suffixAmPm(5); // '5am'suffixAmPm(12); // '12pm'suffixAmPm(15); // '3pm'suffixAmPm(23); // '11pm'
Calculate the number of different days between two dates
const diffDays = (date, otherDate) =>Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24)); // ExamplediffDays(new Date("2014-12-19"), new Date("2020-01-01")); // 1839
Check if a date is valid
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());isDateValid("December 17, 1995 03:24:00"); // true
Miscellaneous
Check if the code is running in Node.js
const isNode =typeof process !== "undefined" &&process.versions != null &&process.versions.node != null;
Check if the code is running in the browser
const isBrowser = typeof window === "object" && typeof document === "object";
Convert URL parameters to object
const getUrlParams = (query) =>Array.from(new URLSearchParams(query)).reduce((p, [k, v]) =>Object.assign({}, p, {[k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v,}),{}); // ExamplesgetUrlParams(location.search); // Get the parameters of the current URLgetUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }// Duplicate keygetUrlParams("foo=Foo&foo=Fuzz&bar=Bar"); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
Detect dark mode
const isDarkMode =window.matchMedia &&window.matchMedia("(prefers-color-scheme: dark)").matches;
Swap two variables
[a, b] = [b, a];
Copy to clipboard
const copyToClipboard = (text) => navigator.clipboard.writeText(text); // ExamplecopyToClipboard("Hello World");
Convert RGB to Hex
const rgbToHex = (r, g, b) =>"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); // ExamplergbToHex(0, 51, 255); // #0033ff
Generate a random hex color
const randomColor = () =>`#${Math.random().toString(16).slice(2, 8).padEnd(6, "0")}`; // Orconst randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;
Generate a random IP address
const randomIp = () =>Array(4).fill(0).map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)).join("."); // ExamplerandomIp(); // 175.89.174.131
Generate a random string using the Node crypto module
const randomStr = () => require("crypto").randomBytes(32).toString("hex");
Conclusion
Don’t forget to clap 👏 in the comment section below if you learned something new