Home Web Front-end Front-end Q&A 33 very practical JavaScript one-line codes, it is recommended to collect them!

33 very practical JavaScript one-line codes, it is recommended to collect them!

Jan 12, 2022 pm 05:22 PM
html javascript front end

This article brings you 33 very practical JavaScript one-line codes, organized and shared with you. These methods use some APIs to simplify the operation, but some methods are not very elegant to write one line, so here are the main ones Learn how to use API! I hope everyone has to help.

33 very practical JavaScript one-line codes, it is recommended to collect them!

1. Date processing

1. Check whether the date is valid

This method is used to check whether the given date is valid:

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

2. Calculate the interval between two dates

This method is used Calculate the time interval between two dates:

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2021-11-3"), new Date("2022-2-1"))  // 90
Copy after login

3. Find the day of the year on which the date is located

This method is used to detect the given date The day of the year:

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

2021 has passed

4. Time formatting

This method can be used to convert time The format of hour:minutes:seconds:

const timeFromDate = date => date.toTimeString().slice(0, 8);
    
timeFromDate(new Date(2021, 11, 2, 12, 30, 0));  // 12:30:00
timeFromDate(new Date());  // 返回当前时间 09:00:00
Copy after login

2. String processing

1. Capitalize the first letter of the string

This method is used to capitalize the first letter of an English string:

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world")  // Hello world
Copy after login

2. Flip the string

This method is used to Flip a string and return the flipped string:

const reverse = str => str.split('').reverse().join('');
reverse('hello world');   // 'dlrow olleh'
Copy after login

3. Random string

This method is used to generate a random string:

const randomString = () => Math.random().toString(36).slice(2);
randomString();
Copy after login

4. Truncate the string

This method can truncate the string from the specified length:

const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;
truncateString(&#39;Hi, I should be truncated because I am too loooong!&#39;, 36)   // &#39;Hi, I should be truncated because...&#39;
Copy after login

5. Remove the string HTML in

This method is used to remove HTML elements from a string:

const stripHtml = html => (new DOMParser().parseFromString(html, &#39;text/html&#39;)).body.textContent || &#39;&#39;;
Copy after login

3. Array processing

1. Remove duplicate items from the array

This method is used to remove duplicate items from the array:

const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
Copy after login

2. Judge the array Whether it is empty

This method is used to determine whether an array is an empty array. It will return a Boolean value:

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

3. Merge two arrays

You can use the following two methods to merge two arrays:

const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];
Copy after login

4. Number operations

1. Determine whether a number is odd or even

This method is used to determine whether a number is odd or even:

const isEven = num => num % 2 === 0;
isEven(996);
Copy after login

2. Obtain the average of a set of numbers

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5);   // 3
Copy after login

3. Get a random integer between two integers

This method is used to get a random integer between two integers

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50);
Copy after login

4. Rounding to specified digits

This method is used to round a number to specified digits:

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56
Copy after login

5. Color operation

1. Convert RGB to hexadecimal mechanism

This method can convert an RGB color value into a hexadecimal value:

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(255, 255, 255);  // &#39;#ffffff&#39;
Copy after login

2. Get a random hexadecimal color

This method is used to get a random hexadecimal color value:

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

6. Browser operation

1. Copy the content to the clipboard

This method uses navigator.clipboard.writeText To copy text to the clipboard:

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

2. Clear all cookies

This method can access cookies and clear them stored in the web page by using document.cookie All cookies:

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

3. Get the selected text

This method gets the text selected by the user through the built-in getSelection property:

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

4. Detect whether it is dark mode

This method is used to detect whether the current environment is dark mode, it is a Boolean value:

const isDarkMode = window.matchMedia && window.matchMedia(&#39;(prefers-color-scheme: dark)&#39;).matches
console.log(isDarkMode)
Copy after login

5. Scroll Go to the top of the page

This method is used to return to the top of the page:

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

6. Determine whether the current tab is activated

The This method is used to detect whether the current tab page has been activated:

const isTabInView = () => !document.hidden;
Copy after login

7. Determine whether the current device is an Apple device

This method is used to detect whether the current device is an Apple device Device:

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
isAppleDevice();
Copy after login

8. Whether to scroll to the bottom of the page

This method is used to determine whether the page has reached the bottom:

const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
Copy after login

9. Redirect to a URL

This method is used to redirect to a new URL:

const redirect = url => location.href = url
redirect("https://www.google.com/")
Copy after login

10. Open the browser print box

This method is used to open the print box of the browser:

const showPrintDialog = () => window.print()
Copy after login

7. Other operations

1. Random Boolean value

This method can return a random Boolean value. Use Math.random() to get a random number from 0-1. Compared with 0.5, there is a half probability of getting a true or false value. .

const randomBoolean = () => Math.random() >= 0.5;
randomBoolean();
Copy after login

2. Variable exchange

You can use the following form to exchange the values ​​​​of two variables when the third variable is not applicable:

[foo, bar] = [bar, foo];
Copy after login

3. Get the type of variable

This method is used to get the type of a variable:

const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
trueTypeOf(&#39;&#39;);     // string
trueTypeOf(0);      // number
trueTypeOf();       // undefined
trueTypeOf(null);   // null
trueTypeOf({});     // object
trueTypeOf([]);     // array
trueTypeOf(0);      // number
trueTypeOf(() => {});  // function
Copy after login

4. Conversion between Fahrenheit and Celsius

该方法用于摄氏度和华氏度之间的转化:

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
celsiusToFahrenheit(15);    // 59
celsiusToFahrenheit(0);     // 32
celsiusToFahrenheit(-20);   // -4
fahrenheitToCelsius(59);    // 15
fahrenheitToCelsius(32);    // 0
Copy after login

5. 检测对象是否为空

该方法用于检测一个JavaScript对象是否为空:

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
Copy after login

【相关推荐:javascript学习教程

The above is the detailed content of 33 very practical JavaScript one-line codes, it is recommended to collect them!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles