An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
January 4, 2022 03:53 pm GMT
Original Link: https://dev.to/everlyhealth/our-favorite-javascript-one-liners-3l7n
Our favorite javascript one-liners
These are our favorite one-liners that we've used and forgot existed because they work so well .
Generate a random hex color
const color = () => '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');
Remove array duplicates
const removeDuplicates = arr => [...new Set(arr)];
Reverse a string
const reverseString = str => str.split("").reverse().join("");
Clear all cookies
Note: This will not always work because cookies can be set to not be changed from the front-end. (Thanks @lukeshiru!)
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, '=;expires=${new Date(0).toUTCString()};path=/'));
Remove falsy values from an array
const removeFalsyValues = arr => arr.filter(Boolean);
Get the value of a query parameter from a url
Pass in the url and the parameter that you're looking for the value of, and this function will return the value to you
const getQueryParam = (url, param) => new URL(url).searchParams.get(queryParam);
Copy to clipboard
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
Get selected text
const getSelectedText = () => window.getSelection().toString();
Scroll to Top
const scrollToTop = () => window.scrollTo(0, 0);
Scroll to Bottom
const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight);
Toggle a Boolean
const toggleBool = bool => !bool;
Convert Fahrenheit / Celsius
const cToF = (celsius) => celsius * 9/5 + 32;const fToC = (fahrenheit) => (fahrenheit - 32) * 5/9;
Thanks
Special thanks to Fernando, Jos, Patricia and @lukeshiru for adding to this list and optimizing!
Original Link: https://dev.to/everlyhealth/our-favorite-javascript-one-liners-3l7n
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To