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

Six inheritance methods in JS and their advantages and disadvantages

Table of contents Preface Prototype chain inherit...

Sample code for implementing neon button animation effects with CSS3.0

Today I will share with you a neon button animati...

How to change password in MySQL 5.7.18

How to change the password in MySQL 5.7.18: 1. Fi...

MySQL 5.7.20 installation and configuration method graphic tutorial (win10)

This article shares the installation and configur...

Detailed explanation of mysql5.6 master-slave setup and asynchronous issues

Table of contents 1. MySQL master-slave replicati...

How familiar are you with pure HTML tags?

The following HTML tags basically include all exis...

Collection of 25 fonts used in famous website logos

This article collects the fonts used in the logos...

Teach you how to write maintainable JS code

Table of contents What is maintainable code? Code...

MySQL 8.0.13 download and installation tutorial with pictures and text

MySQL is the most commonly used database. You mus...

Several common methods of CSS equal height layout

Equal height layout Refers to the layout of child...

Solution to EF (Entity Framework) inserting or updating data errors

Error message: Store update, insert, or delete st...

How to configure Linux firewall and open ports 80 and 3306

Port 80 is also configured. First enter the firew...

Implementation of element shuttle frame performance optimization

Table of contents background Solution New Questio...

Do you know why vue data is a function?

Official website explanation: When a component is...