29 Useful JavaScript One-liners

In today's article, I mainly want to share with you some one-line coding skills about JavaScript. In these methods, we use some APIs to help us simplify operations. Maybe some methods are not very elegant to write a line. The purpose of this , mainly to further learn the skills of using API, I hope it will be helpful to your study.

Now, let's get into today's content.

1. Copy content to clipboard

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");

2. Clear all cookies

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

3. Get the selected text

const getSelectedText = () => window.getSelection().toString();
getSelectedText();

4. Scroll to the top of

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

5. Determine whether the current tab is activated

const isTabInView = () => !document.hidden;

6. Determine whether the current device is an Apple device

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

7. Whether to scroll to the bottom of the page

const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;

8. Redirect to a URL

const redirect = url => location.href = url
redirect("https://www.google.com/")

9. Open the browser print box

const showPrintDialog = () => window.print()

10. Random Boolean

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

11. Variable exchange

[foo, bar] = [bar, foo];

12. Get the type

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

13. Check if the object is empty

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

14. Check if the date is valid

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 2022 03:24:00");

15. Calculate the interval

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
    
dayDif(new Date("2022-11-3"), new Date("2023-2-1"));

16. Find the day

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

17. Time Formatting

const timeFromDate = date => date.toTimeString().slice(0, 8);
    
timeFromDate(new Date(2022, 11, 2, 12, 30, 0));
timeFromDate(new Date());

18. Capitalize

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world")

19. Flip strings

const reverse = str => str.split('').reverse().join('');reverse('hello world');

20. Random string

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

​​​​​​21. Truncating a string

const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;
truncateString('Hi, I am too loooong!', 12);

22. Remove HTML from String

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

23. Remove duplicates

const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));

24. Check if the array is empty

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);

​​​​​​​​25. Merge two arrays

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

​​​​​​26. Judging whether a number is odd or even

const isEven = num => num % 2 === 0;
isEven(1024);

27. Find the average

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5);

28. Get a random integer

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50);

29. Round to the specified number of

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

Guess you like

Origin blog.csdn.net/qq_41872328/article/details/129053505
29