Share 20 JavaScript one-line codes

Share 20 JavaScript one-line codes

1. Get the value of browser cookie

Retrieve the value of cookie by using document.cookie accessor.

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"


2. 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

3. Copy to clipboard

Text can be easily copied to the clipboard using navigator.clipboard.writeText .

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

copyToClipboard("Hello World");


4. Check if the date is valid

Use the following code snippet to check whether a given date is valid or not.

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00");
// Result: true


5. Find the day of the year

Find a given date.

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

dayOfYear(new Date());
// Result: 272

6. Uppercase strings

Javascript does not have a built-in uppercase function, but we can achieve uppercase using the following code.

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

capitalize("follow for more")
// Result: Follow for more


7. Find the number of days between two dates

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


8. Clear all cookies

You can easily clear all cookie stored in a web page by accessing cookie using document.cookie and clearing it.

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


9. Generate random hexadecimal

You can generate random hexadecimal colors using Math.random and padEnd property.

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

console.log(randomHex());
// Result: #92b008


10. Remove duplicates from an array

You can easily remove duplicates using Set in JavaScript . This is a life saver.

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 ]


11. Get query parameters from URL

You can retrieve query parameters from url easy by passing window.location or the original URLgoole.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);
};


12. Output time from date

We can output the time from a given date in the format of hour::minutes::seconds .

const timeFromDate = date => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"


13. Check if a number is even or odd

const isEven = num => num % 2 === 0;

console.log(isEven(2)); 
// Result: True


14. Find the average of numbers

Use the reduce method to find the average of multiple numbers.

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4);
// Result: 2.5


15. Scroll to Top

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

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

goToTop();


16. Reverse a string

You can easily reverse a string using split , reverse , and join methods.

const reverse = str => str.split('').reverse().join('');

reverse('hello world');     
// Result: 'dlrow olleh'

17. Check if the array is empty

With just one line of code you can check if an array is empty and return true or false .

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]);
// Result: true


18. Get the selected text

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

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

getSelectedText();


19. Shuffle an array

It is very easy to shuffle an array using sort and random methods.

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]


20. Detect 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


Summarize:

This is the end of this article about analyzing 20 JavaScript one-line codes. For more relevant JavaScript one-line code content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • 18 killer JavaScript one-liners
  • 25 JavaScript one-line codes commonly used in development (summary)
  • js to achieve a single line of text scrolling up effect example code
  • js single line message scrolling code, you can add countless

<<:  Implementation of css transform page turning animation record

>>:  Details on using order by in MySQL

Recommend

How to pop up a temporary QQ dialog box to chat online without adding friends

In fact, this is very simple. We add an a tag to ...

How to implement JavaScript's new operator yourself

Table of contents Constructor new Operator Implem...

Summary of the understanding of virtual DOM in Vue

It is essentially a common js object used to desc...

Several commonly used methods for centering CSS boxes (summary)

The first one: Using the CSS position property &l...

Implementation of CSS circular hollowing (coupon background image)

This article mainly introduces CSS circular hollo...

Vue+element implements drop-down menu with local search function example

need: The backend returns an array object, which ...

getdata table table data join mysql method

public function json_product_list($where, $order)...

vue uses Ele.me UI to imitate the filtering function of teambition

Table of contents Problem Description The general...

A brief discussion on the VUE uni-app life cycle

Table of contents 1. Application Lifecycle 2. Pag...

Detailed discussion of several methods for deduplicating JavaScript arrays

Table of contents 1. Set Deduplication 2. Double ...

Basic HTML directory problem (difference between relative path and absolute path)

Relative path - a directory path established based...

Detailed explanation of MySQL slow log query

Slow log query function The main function of slow...