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

Summary of MySQL slow log related knowledge

Table of contents 1. Introduction to Slow Log 2. ...

Comprehensive summary of MYSQL tables

Table of contents 1. Create a table 1.1. Basic sy...

Detailed tutorial on installing Protobuf 3 on Ubuntu

When to install If you use the protoc command and...

Introduction to HTML_PowerNode Java Academy

What is HTML? HTML is a language used to describe...

ul list tag design web page multi-column layout

I suddenly thought of this method when I was writi...

jQuery realizes the scrolling effect of table row data

This article example shares the specific code of ...

Detailed explanation of the transition attribute of simple CSS animation

1. Understanding of transition attributes 1. The ...

Detailed explanation of Windows time server configuration method

Recently, I found that the company's server t...

How to avoid the trap of URL time zone in MySQL

Preface Recently, when using MySQL 6.0.x or highe...

The solution record of Vue failing to obtain the element for the first time

Preface The solution to the problem of not being ...

...

A detailed introduction to Linux file permissions

The excellence of Linux lies in its multi-user, m...

Some ways to solve the problem of Jenkins integrated docker plugin

Table of contents background Question 1 Error 2 E...

Detailed discussion of MySQL stored procedures and stored functions

1 Stored Procedure 1.1 What is a stored procedure...