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

This is the second day of my participation in the November Update Challenge. For details of the event, please check: 2021 Last Update Challenge


Recently, I saw some articles about a line of code in the foreign technical community. I found it very interesting. I sorted it out and shared it with you. I hope it will help you~

These methods use some APIs to simplify the operation, but some methods are not very elegant to write a line, so here we mainly learn the skills of using the API!

1. Date processing

1. Check if the date is valid

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

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

isDateValid("December 17, 1995 03:24:00");  // true
复制代码

2. Calculate the interval between two dates

This method is used to calculate the 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
复制代码

There are 90 days until Chinese New Year~

3. Find the day of the year where the date is located

This method is used to detect which day the given date falls within the year:

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

dayOfYear(new Date());   // 307
复制代码

More than 300 days have passed in 2021~

4. Time formatting

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

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
复制代码

Second, 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
复制代码

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'
复制代码

3. Random String

This method is used to generate a random string:

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

randomString();
复制代码

4. Truncate string

This method truncates a string from a specified length:

const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;

truncateString('Hi, I should be truncated because I am too loooong!', 36)   // 'Hi, I should be truncated because...'
复制代码

5. Remove HTML from String

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

const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
复制代码

3. Array processing

1. Remove duplicates from an array

This method is used to remove duplicates in an array:

const removeDuplicates = (arr) => [...new Set(arr)];

console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
复制代码

2. Check if the array is empty

This method is used to check if an array is empty, it will return a boolean value:

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

isNotEmpty([1, 2, 3]);  // true
复制代码

3. Merge two arrays

Two arrays can be merged using the following two methods:

const merge = (a, b) => a.concat(b);

const merge = (a, b) => [...a, ...b];
复制代码

4. Digital operation

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); 
复制代码

2. Get 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
复制代码

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);
复制代码

4. Round off the specified number of digits

This method is used to round a number to the specified place:

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

round(1.005, 2) //1.01
round(1.555, 2) //1.56
复制代码

Five, color operation

1. Convert RGB to sixteen mechanism

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

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(255, 255, 255);  // '#ffffff'
复制代码

2. Get random hex 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();
复制代码

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");
复制代码

2. Clear all cookies

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

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

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();
复制代码

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('(prefers-color-scheme: dark)').matches

console.log(isDarkMode)
复制代码

5. Scroll to the top of the page

This method is used to go back to the top in the page:

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

goToTop();
复制代码

6. Determine whether the current tab is active

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

const isTabInView = () => !document.hidden; 
复制代码

7. Determine whether the current device is an Apple device

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

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

isAppleDevice();
复制代码

8. Whether to scroll to the bottom of the page

This method is used to determine whether the page is already at the bottom:

const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
复制代码

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/")
复制代码

10. Open the browser print box

This method is used to open the browser's print box:

const showPrintDialog = () => window.print()
复制代码

7. Other operations

1. Random Boolean

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

const randomBoolean = () => Math.random() >= 0.5;

randomBoolean();
复制代码

2. Variable exchange

The values ​​of two variables can be swapped without a third variable using the following form:

[foo, bar] = [bar, foo];
复制代码

3. Get the type of the 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('');     // string
trueTypeOf(0);      // number
trueTypeOf();       // undefined
trueTypeOf(null);   // null
trueTypeOf({});     // object
trueTypeOf([]);     // array
trueTypeOf(0);      // number
trueTypeOf(() => {});  // function
复制代码

4. Conversion between Fahrenheit and Celsius

This method is used to convert between Celsius and Fahrenheit:

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
复制代码

5. Check if the object is empty

This method is used to check if a JavaScript object is empty:

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
复制代码

That's all for today's article, if you find it useful, give it a like!

Three in a row.gif

Guess you like

Origin juejin.im/post/7025771605422768159