This paper sorts out some practical JavaScript single line code, which is very easy to use~~
Gets the value of the browser CookieFind the cookie value through document.cookie
const cookie = name => `; $`.split(`; $=`).pop().split(';').shift(); cookie('_ga'); // Result: "GA1.2.1929736587.1601974046"Color 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 to clipboard
With the help of navigator.clipboard.writeText, the spoken text can be easily copied to the clipboard
The specification requires that you use before writing to the clipboard Permissions API Get clipboard write permission. However, the specific requirements of different browsers are different, because this is a new API. For more information, see compatibility table and Clipboard availability in Clipboard.
const copyToClipboard = (text) => navigator.clipboard.writeText(text); copyToClipboard("Hello World");Check whether the date is legal
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: trueWhat day of the year is the lookup date
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // Result: 272English string initial capital
Javascript does not have a built-in capital 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 moreCalculate the number of days between 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: 366Clear all cookies
You can easily clear all cookies stored in a web page by accessing and clearing cookies using document.cookie.
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=$;path=/`));Generate random hex color
You can use the Math.random and padEnd properties to generate random hexadecimal colors.
const randomHex = () => `#$`; console.log(randomHex()); // Result: #92b008Array de duplication
You can easily delete 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 ]Get query parameters from 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(/&/g20 October 2021, 16:54 | Views: 3453
Add new comment
0 comments