Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
A journey of a thousand miles begins with single step
This article has put together some useful Single-line JavaScript functions that will help you get your work done faster and spend more time with your girlfriend. Without further ado, let’s begin!
Time and date
-
Check that the date is valid
const isDateValid = (. val) = > !Number.isNaN(new Date(... val).valueOf())console.log(isDateValid("December 17, 1995 03:24:00")) // true Copy the code
-
Check if the date is a weekend
const isWeekend = (date) = > [0.6].indexOf(date.getDay()) ! = = -1 console.log(isWeekend(new Date(2021.5.21))) //false console.log(isWeekend(new Date(2021.5.20))) //true // The current date is Monday, 2021.6.21 Copy the code
-
The day of the year in which the search date is located
const dayOfYear = (date) = > Math.floor((date - new Date(date.getFullYear(), 0.0)) / 1000 / 60 / 60 / 24) // The specified date and month should be subtracted by one console.log(dayOfYear(new Date(2021.8.29))) console.log(dayOfYear(new Date("2021-9-29"))) console.log(dayOfYear(new Date())) / / 272 / / 272 / / 272 Copy the code
-
Calculate the number of days between two dates
const dayDif = (date1, date2) = > Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) console.log(dayDif(new Date("2021-10-1"), new Date("2021-9-30"))) / / 1 Copy the code
-
Time to deal with
const timeFromDate = date= > date.toTimeString().slice(0.8) console.log(timeFromDate(new Date())) console.log(timeFromDate(new Date(2021.0.10.17.30.0))) / / 14:23:36 / / 17:30:00 Copy the code
digital
-
Check whether the numbers are even or odd
const isEven = (num) = > num % 2= = =0 console.log(isEven(5)) // false Copy the code
-
The average of multiple numbers
const average = (. args) = > args.reduce((a, b) = > a + b) / args.length console.log(average(1.2.3.4.5)) / / 3 Copy the code
-
Generate a random number between two numbers
const random = (min, max) = > Math.floor(Math.random() * (max - min + 1) + min) console.log(random(1.50)) // could be anything from 1 - 50 Copy the code
string
-
Flip string
const reverse = str= > str.split(' ').reverse().join(' ') console.log(reverse('hello world')) // dlrow olleh Copy the code
-
Uppercase character string
const capitalize = (str) = > str.charAt(0).toUpperCase() + str.slice(1) console.log(capitalize('hello world')) Copy the code
-
Truncate the string at the end
const truncateString = (string, length) = > { return string.length < length ? string : `${string.slice(0, length - 3)}. ` } console.log(truncateString('Hi, I should be truncated because I am too loooong! '.36)) // Hi, I should be truncated because... Copy the code
-
Truncate the string from the middle
// The function takes a string as the first argument, then the size of the string we want as the second argument, and then how many characters are needed to start and end from the 3rd and 4th arguments const truncateStringMiddle = (string, length, start, end) = > { return `${string.slice(0, start)}.${string.slice(string.length - end)}` } console.log(truncateStringMiddle( 'A long story goes here but then eventually ends! '.// string 25.// The required string size 13.// Start at the number of bits in the original string 17.// Stop intercepting from the original string )) // A long story ... eventually ends! Copy the code
-
Generate random string (unique ID)
const randomString = () = > Math.random().toString(36).slice(2) console.log(randomString()) // could be anything Copy the code
An array of
-
Get a unique value in an array (array decrement)
const uniqueArr = arr= > ([...new Set(arr)]) console.log(uniqueArr([1.2.3.1.2.3.4.5])) // [1, 2, 3, 4, 5] Copy the code
-
Check if the variable is an array
const isArray = (arr) = > Array.isArray(arr) console.log(isArray([1.2.3])) // true console.log(isArray({name:'Ovi'})) // false console.log(isArray('Hello World')) // false Copy the code
-
Disrupted array
const shuffleArray = (arr) = > arr.sort(() = > 0.5 - Math.random()) console.log(shuffleArray([1.2.3.4])) // [1, 3, 2, 4] Copy the code
-
Verifies whether the array is empty
const isNotEmpty = arr= > Array.isArray(arr) && arr.length > 0 console.log(isNotEmpty([1.2.3])) // true Copy the code
-
Different ways to merge multiple arrays
// PS: We can also use the Settings object to copy anything from the final array. / / (1) the concat () / / (2)... const merge = (a, b) = > a.concat(b) const merge = (a, b) = > [...a, ...b] const merge = [...new Set(a.concat(b))] const merge = [...new Set([...a, ...b])] Copy the code
Boolean value
-
Get Boolean values at random
const getRandomBoolean = () = > Math.random() >= 0.5 console.log(getRandomBoolean()) // true/false Copy the code
-
Toggle Boolean
// bool is stored somewhere in the upperscope const toggleBool = () = >(bool = ! bool)//or const toggleBool = b= >! bconsole.log(toggleBool(true)) // false Copy the code
Variable exchange
-
Swap two variables (semicolon required)
let foo = 'foo'; let bar = 'bar'; [foo, bar] = [bar, foo] console.log([foo, bar]) Copy the code
A short circuit
-
Longhand
let str = 'str' if(str ! = =null|| str ! = =undefined|| str ! = =' ') { let fullName = str } Copy the code
-
Shorthand
const fullName = str || buddy Copy the code
To obtainJavaScript
The actual type of language
-
Method A
const trueTypeOf = (obj) = > { return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); } console.log(trueTypeOf(' ')) // string console.log(trueTypeOf(0)) // number console.log(trueTypeOf()) // undefined console.log(trueTypeOf(null)) // null console.log(trueTypeOf({})) // object console.log(trueTypeOf([])) // array console.log(trueTypeOf(0)) // number console.log(trueTypeOf(() = > {})) // function Copy the code
-
Method B
var a = () = > {} function getType(params) { let type = typeof(params) if(type ! = ='object') { return type } return Object.prototype.toString.call(params).replace(/^\[object (\S+)\]$/.'$1')}console.log(getType(a)) // function Copy the code
color
-
Color RGB to hexadecimal
const rgbToHex = (r, g, b) = > "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) console.log(rgbToHex(255.255.255)) // #ffffff Copy the code
-
Generates random hexadecimal colors
const randomHex = () = > ` #The ${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6."0")}` console.log(randomHex()) / / # 680244 Copy the code
Cookie
-
Gets the value of the browser Cookie
const cookie = name= > `; The ${document.cookie}`.split(`; ${name}= `).pop().split('; '). The shift () XXX for the keyconsole.log(cookie('XXX')) Copy the code
-
Clear all cookies
const clearCookies = document.cookie.split('; ').forEach(cookie= > document.cookie = cookie.replace(/ ^ + /.' ').replace(/ =. * /.` =; expires=The ${new Date(0).toUTCString()}; path=/`)) Copy the code
Get query parameters from the URL
-
Method A
const getParameters = (URL) = > { URL = JSON.parse( '{"' + decodeURI(URL.split("?") [1]) .replace(/"/g.'\ \ "') .replace(/&/g.'",") .replace(/=/g.'" : "') + '"}' ) return JSON.stringify(URL) } getParameters(window.location) Copy the code
-
Method B
Object.fromEntries(new URLSearchParams(window.location.search)) Copy the code
The mobile terminal
-
Check if the user is on an Apple device
const isAppleDevice = () = > /Mac|iPod|iPhone|iPad/.test(navigator.platform) console.log(isAppleDevice) // true/false Copy the code
-
Check whether the user’s device is in dark mode
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches console.log(isDarkMode) // true/false Copy the code
other
-
Scroll to the top of the page
const scrollToTop = () = > window.scrollTo(0.0) scrollToTop() Copy the code
-
Copy text to clipboard
/ / you may need to add a check to see whether there is the navigator, clipboard. WriteText const copyTextToClipboard = async (text) => { await navigator.clipboard.writeText(text) } Copy the code
-
Gets the text selected by the user
const getSelectedText = () = > window.getSelection().toString(); getSelectedText() Copy the code
-
Check if the current TAB is in view/focus
const isTabInView = () = > !document.hidden // Not hidden isTabInView() // true/false Copy the code