Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use a single line of JavaScript code

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use JavaScript single-line code", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "how to use JavaScript single-line code" bar!

What is a single line of code?

A single line of code is a code practice in which we perform certain functions with only one line of code.

Single-line code example

1. Copy to the 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 whether the date is valid

Use the following code snippet to check whether the given date is valid.

Const isDateValid = (... val) = >! Number.isNaN (new Date (.. Val). ValueOf (); isDateValid ("December 17, 1995 03:24:00"); / / Result: true

3. Find out which day of the year

Find which day on 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 doesn't have built-in uppercase functions, 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 out the number of days between two dates

Use the following code snippet to find the number of days between a 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 Cookie

You can easily clean up all cookie stored in a web page by accessing cookie using [xss_clean] and clearing it.

Const clearCookies = [xss_clean] .split (';') .forEach (cookie = > [xss_clean] = cookie.replace (/ ^ + /,''). Replace (/ =. * /, `=; expires=$ {new Date (0). ToUTCString ()}; path=/`))

7. Generate random hexadecimal

You can use the Math.random and padEnd attributes 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 the array

You can easily delete 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 easily retrieve query parameters from url by passing _ window.location or raw 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 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 whether the number is even or odd

Const isEven = num = > num% 2 = = 0bot console.log (isEven (2)); / / Result: True

12. Find the average of the number

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 the string

You can easily reverse strings using the split, reverse, and join methods.

Const reverse = str = > str.split (''). Reverse (). Join (''); reverse ('hello world'); / / Result:' dlrow olleh'

14. Check whether the array is empty

A simple one-line program that checks whether the array is empty will return true or false.

Const isNotEmpty = arr = > Array.isArray (arr) & & arr.length > 0terisNotEmpty ([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. Scramble the array

It is very easy to scramble the 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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report