Commonly Used JavaScript Utility Functions
Ryan GanPublished on Sep 20, 2024
2 min read
In this post, I will introduce 9 JavaScript utility functions that are commonly used in modern JavaScript applications.
1. Copy Text to Clipboard
JavaScript
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
// example usage
copyToClipboard('Hello, World!');2. Get nth Day of the Year
JavaScript
const getDayOfYear = (date) => {
// Both dates at UTC midnight, so a daylight saving change in between
// cannot leave a day an hour short
const day = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());
// Day zero is December 31 of the year before
const dayZero = Date.UTC(date.getFullYear(), 0, 0);
return (day - dayZero) / (24 * 60 * 60 * 1000);
};
// example usage
getDayOfYear(new Date(2024, 8, 20)); // 264 (months start at 0: 8 is September)3. Remove Duplicates from an Array
JavaScript
const removeDuplicates = (arr) =>
arr.filter((item, index) => arr.indexOf(item) === index);
// example usage
removeDuplicates([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]4. Select a Random Item from an Array
JavaScript
const selectRandomItem = (arr) => arr[Math.floor(Math.random() * arr.length)];
// example usage
selectRandomItem([1, 2, 3, 4, 5]); // A random number between 1 and 55. Grayscale a RGB Color Value (Based on the luminance of the color)
JavaScript
const grayScale = (r, g, b) => 0.2126 * r + 0.7152 * g + 0.0722 * b;
// example usage
grayScale(255, 255, 255);6. Parse Query Parameters from a URL
JavaScript
const parseQuery = (url) => Object.fromEntries(new URL(url).searchParams);
// example usage
parseQuery('https://example.com?foo=bar&baz=qux');
// {foo: 'bar', baz: 'qux'}7. Pick Keys from an Object
JavaScript
const pick = (obj, ...keys) =>
Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)));
// example usage
pick({ a: 1, b: 2, c: 3 }, 'a', 'c'); // {a: 1, c: 3}8. Get a Random Hex Color
JavaScript
const getRandomHexColor = () => {
const color = Math.floor(Math.random() * 0x1000000); // 0x000000 to 0xffffff
return '#' + color.toString(16).padStart(6, '0');
};
// example usage
getRandomHexColor();9. Remove Tag from HTML
JavaScript
const removeTag = (fragment) =>
new DOMParser().parseFromString(fragment, 'text/html').body.textContent || '';
// example usage
removeTag('<p>Hello, World!</p>'); // 'Hello, World!'Thank you for reading! I hope you found this helpful!
Happy coding!