18 killer JavaScript single line code

  1. home page
  2. special column
  3. Vue starts from scratch
  4. Article details
0

18 killer JavaScript single line code

CRMEB Published 8 minutes ago

1. Copy to clipboard

Easily copy any text to the clipboard using navigator.clipboard.writeText.

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
Copy 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: true
 Copy code

3. Find out which 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 code

4. Capitalize first string

Javascript has no built-in uppercase 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 code

5. Find the number of days between two dates

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

6. Clear all cookies

You can easily clear all cookies stored in the web page by using document.cookie to access the cookie and clear it.

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

7. Generate random hex

You can use the 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: #92b008
 Copy code

8. Remove duplicates from array

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

9. Get query parameters from URL

You can easily retrieve query parameters from the url by passing window.location or the original url goose. 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 code

10. Record time from date

We can record time in the format of hour:: minute:: second 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 code

11. Check whether the number is even or odd

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

12. Average the numbers

Use the reduce 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
 Copy code

13. Reverse string

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

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

14. Check whether the array is empty

A simple single line program that checks whether the array is empty will return true or false.

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

15. Gets the selected text

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

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

16. Scramble array

Using the sort and random methods, it's very easy to disrupt arrays.

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

17. Detect dark mode

Use the following code to check whether 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 code

18. Convert 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 code

last
If you think this article is a little helpful to you, give it a compliment. Or you can join my development exchange group: 1025263163 learn from each other, and we will have professional technical Q & A to solve doubts

If you think this article is useful to you, please click star: https://gitee.com/ZhongBangKeJi esteem it a favor!

Reading 10 was published 8 minutes ago
Like collection
Vue starts from scratch
Vue hands-on introduction, learn from zero and disassemble every knowledge point!
Focus column

CRMEB new retail social e-commerce member management marketing system!

42 prestige
6 fans
Focus on the author
Submit comments
You know what?

Register login

CRMEB new retail social e-commerce member management marketing system!

42 prestige
6 fans
Focus on the author
Article catalog
follow
Billboard

Tags: Javascript

Posted on Fri, 29 Oct 2021 01:36:52 -0400 by pankirk