1. Get the value of browser cookie Retrieve the value of const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift(); cookie('_ga'); // Result: "GA1.2.1929736587.1601974046" 2. Convert RGB to Hexadecimalconst rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); rgbToHex(0, 51, 255); // Result: #0033ff 3. Copy to clipboard Text can be easily copied to the clipboard using const copyToClipboard = (text) => navigator.clipboard.writeText(text); copyToClipboard("Hello World"); 4. Check if the date is valid Use the following code snippet to check whether a given date is valid or not. const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf()); isDateValid("December 17, 1995 03:24:00"); // Result: true 5. Find the day of the year Find a given date. const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // Result: 272 6. Uppercase strings const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1) capitalize("follow for more") // Result: Follow for more 7. Find the number of days between two dates Use the following code snippet to find the number of days between the given two dates. const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) dayDif(new Date("2020-10-21"), new Date("2021-10-22")) // Result: 366 8. Clear all cookies You can easily clear all const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)); 9. Generate random hexadecimal You can generate random hexadecimal colors using const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`; console.log(randomHex()); // Result: #92b008 10. Remove duplicates from an array You can easily remove duplicates using const removeDuplicates = (arr) => [...new Set(arr)]; console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6])); // Result: [ 1, 2, 3, 4, 5, 6 ] 11. Get query parameters from URL You can retrieve query parameters from const getParameters = (URL) => { URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}'); return JSON.stringify(URL); }; 12. Output time from date We can output the time from a given date in the format of const timeFromDate = date => date.toTimeString().slice(0, 8); console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); // Result: "17:30:00" 13. Check if a number is even or oddconst isEven = num => num % 2 === 0; console.log(isEven(2)); // Result: True 14. Find the average of numbers Use the const average = (...args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4); // Result: 2.5 15. Scroll to Top We can use the const goToTop = () => window.scrollTo(0, 0); goToTop(); 16. Reverse a string You can easily reverse a string using const reverse = str => str.split('').reverse().join(''); reverse('hello world'); // Result: 'dlrow olleh' 17. Check if the array is empty With just one line of code you can check if an array is empty and return const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0; isNotEmpty([1, 2, 3]); // Result: true 18. Get the selected text Use the built-in const getSelectedText = () => window.getSelection().toString(); getSelectedText(); 19. Shuffle an array It is very easy to shuffle an array using const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random()); console.log(shuffleArray([1, 2, 3, 4])); // Result: [ 1, 4, 3, 2 ] 20. Detect Dark Mode Use the following code to check if the user's device is in dark mode. const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches console.log(isDarkMode) // Result: True or False Summarize: This is the end of this article about analyzing 20 You may also be interested in:
|
<<: Implementation of css transform page turning animation record
>>: Details on using order by in MySQL
Table of contents Preface Prototype chain inherit...
Today I will share with you a neon button animati...
How to change the password in MySQL 5.7.18: 1. Fi...
This article shares the installation and configur...
Table of contents 1. MySQL master-slave replicati...
The following HTML tags basically include all exis...
This article collects the fonts used in the logos...
Table of contents What is maintainable code? Code...
MySQL is the most commonly used database. You mus...
Equal height layout Refers to the layout of child...
Error message: Store update, insert, or delete st...
Port 80 is also configured. First enter the firew...
Overview of Alibaba Cloud Security Group Sharing ...
Table of contents background Solution New Questio...
Official website explanation: When a component is...