random array
Shuffling an array using the sort
and random
methods is very common.
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4]));
// 结果:[ 1, 4, 3, 2 ]
Check if 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");
// 结果:真
copy to clipboard
Copy any text to the clipboard navigator.clipboard.writeText
.
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
Find the day of the year
Find which day of a given date.
const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// 结果:272
uppercase string
Javascript
has no built-in uppercase function, so we can handle it with the following code.
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello")
// 结果:Hello
Find the number of days between two days
Use the following code snippet to find the number of days between 2 days.
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// 结果:366
clear all cookies
All cookie
stored on web pages can be easily cleared by document.cookie
and clearing cookie
.
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=$ {new Date(0).toUTCString()};path=/`));
Generate random hex
Random hex colors can be generated using the Math.random
and padEnd
properties.
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
// 结果:#92b008
remove duplicates from an array
Duplicates can be easily removed using Set
.
const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// 结果:[ 1, 2, 3, 4, 5, 6 ]
Get query parameters from URL
Query parameters goole.com?search=easy&page=3
can be easily retrieved from URL
, bypassing window.location
or the original URL
const getParameters = (URL) => {
URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace (/&/g, '","').replace(/=/g, '":"') +'"}');
返回 JSON.stringify(URL);
};
getParameters(window.location)
// 结果:{ search : "easy", page : 3 }
record time from date
We can record the time in the format hour::minutes::seconds
for a given date.
const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// 结果:“17:30:00”
Check if a number is even or odd
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// 结果:真
find the average of numbers
reduce
uses the method to find the average between multiple numbers.
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// 结果:2.5
Check if array is empty
A simple function to check if the array is empty will return true
or false
.
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// 结果:真
get selected text
getSelection
uses a built-in property to get the text selected by the user.
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
Detect if in 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);
// 结果:真或假
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。