PrefaceJavaScript continues to grow and prosper because it is one of the easiest languages to pick up, thus opening the door for new tech geeks in the market. And, whether you’re new to JavaScript or a more of a professional developer, learning something new is always a good thing. This article has compiled some very useful one-liners that can help you improve your work efficiency. What is a one-line code?
One-line code example1. Copy to clipboard Use navigator.clipboard.writeText to easily copy any text to the clipboard. const copyToClipboard = (text) => navigator.clipboard.writeText(text); copyToClipboard("Hello World"); 2. 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 3. Find out the day of the year Find the day of a given date. const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // Result: 272 4. Capitalize the first string Javascript does not have a built-in uppercase function, so we can use the following code. const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)capitalize("follow for more") // Result: Follow for more 5. Find the number of days between two dates Use the following code snippet to find the number of days between the given 2 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 6. Clear all cookies You can easily clear all cookies stored in a web page by accessing the cookies using document.cookie and clearing it. const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '') .replace(/=.*/, `=;expires=${new Date(0).toUTCString()}; path=/`)); 7. Generate random hexadecimal You can use Math.random and the padEnd property to generate random hexadecimal colors. const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}` console.log(randomHex()); //Result: #92b008 8. Remove duplicates from an array You can easily remove duplicates using Set in JavaScript. 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 ] 9. Get query parameters from URL You can retrieve query parameters from the url easily by passing window.location or the original URL goole.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); }; getParameters(window.location) // Result: { search : "easy", page : 3 } 10. Record time from date We can record the time in the format hours::minutes::seconds from a given date. const timeFromDate = date => date.toTimeString().slice(0, 8); console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); // Result: "17:30:00" 11. Check if a number is even or odd const isEven = num => num % 2 === 0; console.log(isEven(2)); // Result: True 12. Find the average of numbers Use the reduce method to find the average between multiple numbers. const average = (...args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4); // Result: 2.5 13. Reverse a string You can easily reverse a string using the split, reverse, and join methods. const reverse = str => str.split('').reverse().join('');reverse('hello world'); // Result: 'dlrow olleh' 14. Check if the array is empty A simple one-liner that checks if an array is empty will return true or false. const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0; isNotEmpty([1, 2, 3]); // Result: true 15. Get the selected text Use the built-in getSelectionproperty to get the text selected by the user. const getSelectedText = () => window.getSelection().toString(); getSelectedText(); 16. Shuffle the array It is very easy to shuffle an array using the 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 ] 17. 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)').matchesconsole.log(isDarkMode) // Result: True or False 18. 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 SummarizeThis is the end of this article about JavaScript one-line code. For more relevant JavaScript one-line code content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Some common mistakes with MySQL null
>>: Beginners learn some HTML tags (3)
When you install MySQL, you will be given an init...
Background: A long time ago (2017.6.5, the articl...
Preface Now the operating system used by my compa...
The previous three articles introduced common bac...
Official website address: https://dev.mysql.com/d...
Table of contents 1. The direction of this in the...
As a technical novice, I am recording the process...
Table of contents 1. What is an index signature? ...
Let’s look at an example first Copy code The code ...
When a company builds Docker automated deployment...
1. Problem The docker container logs caused the h...
Using js in web design can achieve many page effec...
The solution to the problem that Navicat cannot r...
Mac node delete and reinstall delete node -v sudo...
Table of contents 1. Scene introduction 2 Code Op...