Copy to Clipboard Link to heading

const copyToClipboard = (text) => navigator.clipboard.writeText(text)

copyToClipboard('Copy me')

Random number in a range Link to heading

const randomNumberInRange = (min = 0, max = 100) => 
    Math.floor(Math.random() * (max - min + 1)) + min;
 
randomNumberInRange()
// Result: Default random number range is 0 - 100, so you get a number between 0 and 100.
randomNumberInRange(100, 200)
// Result: You will get a random number between 100 and 200, where 100 is min range and 200 is max range.

RGB to HEX Link to heading

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

Scroll to top Link to heading

const goToTop = () => window.scrollTo(0, 0)
 
goToTop();

Day difference between two dates Link to heading

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

Random hex number Link to heading

const randomHex = () => 
    `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`

is weekDay Link to heading

const isWeekday = (date) => date.getDay() % 6 !== 0
 
console.log(isWeekday(new Date(2021, 0, 11)))
// Result: true (Monday)
console.log(isWeekday(new Date(2021, 0, 10)))
// Result: false (Sunday)

Is Apple (this API is deprecated and will be phased out) in the future Link to heading

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
 
console.log(isAppleDevice);
// Result: will return true if user is on an Apple device

Time from date Link to heading

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

HTML Tag removal Link to heading

const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || ''
 
console.log(stripHtml('<h1>Hello <strong>World</strong>!!!</h1>'))
// Result: Hello World!!!

HTML string reversal Link to heading

const stringReverse = str => str.split("").reverse().join("")
 
stringReverse('elcitra ym ekil uoy epoh i')
// Result: i hope you like my article

Capitalise first letter in a string Link to heading

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

console.log(capitalize('hello'))
// Result: Hello

Round float point to specific precision Link to heading

// Default Javascript function toFixed behaviour
Number((1.005).toFixed(2)) //outputs 1 instead of 1.01
Number((1.555).toFixed(2)) //outputs 1.55 instead of 1.56

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

round(1.005, 2) //1.01
round(1.555, 2) //1.56

Shuffle array Link to heading

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random())
 
console.log(shuffleArray([1, 2, 3, 4]))
// Result: [ 1, 4, 3, 2 ]

Is dark mode Link to heading

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
 
console.log(isDarkMode) // Result: True or False

Get params from URL as json Link to heading

const getParameters = (URL) => JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
 
console.log(getParameters("https://www.google.de/search?q=cars&start=40"))
// Result: { q: 'cars', start: '40' }

Average number from array Link to heading

const average = arr => arr.reduce((a, b) => a + b) / arr.length;
 
average([21, 56, 23, 122, 67])
//57.8

Is touch supported Link to heading

const touchSupported = () => 
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch)
 
console.log(touchSupported())
// Result: will return true if touch events are supported, false if not

Day of Year Link to heading

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

Clear all cookies Link to heading

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

Random boolean Link to heading

const randomBoolean = () => Math.random() >= 0.5;

console.log(randomBoolean());
// Result: a 50/50 change on returning true of false

Remove duplicates in array Link to heading

const removeDuplicates = (arr) => [...new Set(arr)];
 
removeDuplicates([31, 56, 12, 31, 45, 12, 31]);
//[ 31, 56, 12, 45 ]

Validate is date valid Link to heading

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

Get Random array item Link to heading

const randomArrayItem = (arr) => arr[Math.floor(Math.random() * arr.length)];

randomArrayItem(['lol', 'a', 2, 'foo', 52, 'Jhon', 'hello', 57]);
// Result: It will be some random item from array

Remove all empty key-values from an object Link to heading

let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v));