1. Copy to clipboard

Use the navigator. Clipboard. WriteText easily to any text copied to the clipboard.

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
Copy the code

2, check whether the date is valid

Use the following code snippet to check if the given date is valid.

const isDateValid = (... val) => ! Number.isNaN(new Date(... val).valueOf()); isDateValid("December 17, 1995 03:24:00"); // Result: trueCopy the code

3. Find out the day of the year

Find the day of a given date.

const dayOfYear = (date) =>  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// Result: 272
Copy the code

4. Capitalize the string

Javascript does not have a built-in capitalization function, so we can use the following code.

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)capitalize("follow for more")// Result: Follow for more
Copy the code

Find the number of days between the two dates

Use the following code snippet to find the number of days between the given 2 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
Copy the code

6. Clear all cookies

You can easily clear all cookies stored in a web page by accessing the cookie using document.cookie and clearing it.

const clearCookies = document.cookie.split('; ').forEach(cookie => document.cookie = cookie.replace(/^ +/, '') .replace(/=.*/, `=; expires=${new Date(0).toUTCString()}; path=/`));Copy the code

Generate random hexadecimal

You can use math. random and padEnd properties to generate random hexadecimal colors.

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}` console.log(randomHex());  //Result: #92b008Copy the code

Delete duplicates from array

You can easily remove duplicates using Set in JavaScript.

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 ]
Copy the code

9. Get query parameters from the URL

You can easily retrieve query parameters from the URL by passing window.location or the original URL goole.com? Search =easy&page=3

const getParameters = (URL) => { URL = JSON.parse('{"' + decodeURI(URL.split("?" )[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace( /=/g, '":"') + '"}'); return JSON.stringify(URL); }; getParameters(window.location) // Result: { search : "easy", page : 3 }Copy the code

Record the time from the date

We can record the time in hours :: minutes :: seconds from a given date.

const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"
Copy the code

11. Check whether the numbers are even or odd

const isEven = num => num % 2 === 0; console.log(isEven(2)); // Result: TrueCopy the code

12. Average the numbers

Use the Reduce method to find the average between multiple numbers.

const average = (... args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4); / / Result: 2.5Copy the code

13. Reverse the string

You can easily reverse strings using the split, reverse, and join methods.

const reverse = str => str.split('').reverse().join(''); reverse('hello world'); // Result: 'dlrow olleh'Copy the code

Check whether the array is empty

A simple one-line program that checks if the array is empty returns true or false.

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true
Copy the code

15. Get the selected text

Get the user-selected text using the built-in getSelectionproperty.

const getSelectedText = () => window.getSelection().toString();
getSelectedText();
Copy the code

16. Scramble arrays

Scrambling an array is easy with the sort and random methods.

Const shuffleArray = (arr) => arr.sort(() => 0.5 - math.random ()); console.log(shuffleArray([1, 2, 3, 4])); // Result: [ 1, 4, 3, 2 ]Copy the code

17. 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)').matchesconsole.log(isDarkMode) // Result: True or False
Copy the code

18. Convert RGB to hex

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); rgbToHex(0, 51, 255); // Result: #0033ffCopy the code

conclusion

Please keep these 18 very practical JavaScript One Lines in your collection. If you have any questions, please remember to tell me in the comment section. If you think today’s content is very helpful to you, please remember to share it with your friends who are doing development.

Finally, thank you for your time and for reading.