20 Useful JavaScript One-liners

Get the value of the browser cookie

document.cookieLook up cookiethe value by

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
    
cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"

Color RGB to hexadecimal

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

copy to clipboard

navigator.clipboard.writeTextCopy text to clipboard easily with

The specification requires the "clipboard write" permission to be obtained using the Permissions API before writing to the clipboard. However, the exact requirements vary from browser to browser because this is a new API. See compatibility table and Clipboard availability in Clipboard for details. 

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

Check if the date is legal

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

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

Find the day of the year in which the date falls

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

Capitalize the first letter of the English 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

Calculate the difference in days between 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

clear all cookies

document.cookieAll cookies stored in web pages can be easily cleared by using access cookies and clearing them.

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

Generate random hex colors

 Random hex colors can be generated using  Math.random the and  attributes.padEnd

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

Array deduplication

SetDuplicates can be easily removed using JavaScript in

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

 Query parameters can be easily retrieved from url by passing  window.location or raw 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 }

or even simpler:

Object.fromEntries(new URLSearchParams(window.location.search))
// Result: { search : "easy", page : 3 }

time processing

We can record time from a given date in  hour::minutes::seconds format.

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

Whether the check digit is odd or even

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

average of numbers

Use reducethe method to find the average value between multiple numbers.


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

back to the top

You can use  window.scrollTo(0, 0) the method to automatically scroll to the top. Set  both x and  y to 0.

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

flip string

Strings can be easily reversed using  splitthe , reverse and  join methods.

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

Check if the array is empty

One line of code that checks if the array is empty will return trueeitherfalse

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

Get the text selected by the user

Use the built-in getSelection properties to get the text selected by the user.

const getSelectedText = () => window.getSelection().toString();
    
getSelectedText();

Shuffle the array

Arrays can be shuffled using sort the and  random methods

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

Check if the user's device is 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) 
// Result: True or False

Guess you like

Origin blog.csdn.net/weixin_54165147/article/details/123392970