33 Extremely Useful JavaScript One-Liners
# 1. Date Handling
# 1. Check Whether a Date Is Valid
This method checks whether a given date is valid:
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00"); // true
2
3
# 2. Calculate the Number of Days Between Two Dates
This method calculates 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
2
3
90 days until the new year~
# 3. Find the Day of the Year for a Given Date
This method determines which day of the year the given date falls on:
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 307
2
3
Over 300 days of 2021 have already passed~
# 4. Format Time
This method converts a date to the 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()); // returns the current time 09:00:00
2
3
4
# 2. String Handling
# 1. Capitalize the First Letter of a String
This method capitalizes the first letter of an English string:
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world") // Hello world
2
3
# 2. Reverse a String
This method reverses a string and returns the result:
const reverse = str => str.split('').reverse().join('');
reverse('hello world'); // 'dlrow olleh'
2
3
# 3. Generate a Random String
This method generates a random string:
const randomString = () => Math.random().toString(36).slice(2);
randomString();
2
3
# 4. Truncate a String
This method truncates a string at 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...'
2
3
# 5. Strip HTML from a String
This method removes HTML elements from a string:
const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
# 3. Array Handling
# 1. Remove Duplicates from an Array
This method removes duplicate items from an array:
const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
2
3
# 2. Check Whether an Array Is Empty
This method checks whether an array is empty, returning a boolean:
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]); // true
2
3
# 3. Merge Two Arrays
You can use either of these two approaches to merge two arrays:
const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];
2
3
# 4. Number Operations
# 1. Check Whether a Number Is Odd or Even
This method determines whether a number is odd or even:
const isEven = num => num % 2 === 0;
isEven(996);
2
3
# 2. Calculate 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
2
3
# 3. Get a Random Integer Between Two Integers
This method returns a random integer within a given range:
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50);
2
3
# 4. Round a Number to a Specified Number of Decimal Places
This method rounds a number to a given number of decimal places:
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56
2
3
4
# 5. Color Operations
# 1. Convert RGB to Hexadecimal
This method converts an RGB color value to its hexadecimal representation:
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(255, 255, 255); // '#ffffff'
2
3
# 2. Generate a Random Hexadecimal Color
This method generates a random hexadecimal color value:
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
randomHex();
2
3
# 6. Browser Operations
# 1. Copy 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
3
# 2. Clear All Cookies
This method accesses document.cookie and clears all cookies stored by the page:
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 retrieves the text the user has selected using the built-in getSelection property:
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
2
3
# 4. Detect Dark Mode
This method checks whether the current environment is in dark mode, returning a boolean:
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode)
2
3
# 5. Scroll to the Top of the Page
This method scrolls the page back to the top:
const goToTop = () => window.scrollTo(0, 0);
goToTop();
2
3
# 6. Check Whether the Current Tab Is Active
This method checks whether the current browser tab is active:
const isTabInView = () => !document.hidden;
# 7. Check Whether the Current Device Is an Apple Device
This method detects whether the current device is an Apple device:
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
isAppleDevice();
2
3
# 8. Check Whether the Page Has Been Scrolled to the Bottom
This method checks whether the page has been scrolled all the way to the bottom:
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
# 9. Redirect to a URL
This method redirects to a new URL:
const redirect = url => location.href = url
redirect("https://www.google.com/")
2
3
# 10. Open the Browser Print Dialog
This method opens the browser's print dialog:
const showPrintDialog = () => window.print()
# 7. Miscellaneous
# 1. Generate a Random Boolean
This method returns a random boolean. Using Math.random() to generate a number between 0 and 1, there is a 50/50 chance of getting true or false.
const randomBoolean = () => Math.random() >= 0.5;
randomBoolean();
2
3
# 2. Swap Variables
You can swap two variables without a third variable using the following syntax:
[foo, bar] = [bar, foo];
# 3. Get the Type of a Variable
This method retrieves 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
2
3
4
5
6
7
8
9
10
# 4. Convert Between Fahrenheit and Celsius
These methods 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
2
3
4
5
6
7
8
# 5. Check Whether an Object Is Empty
This method checks whether a JavaScript object is empty:
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
Author: CUGGZ Link: https://juejin.cn/post/7025771605422768159