This paper sorts out some practical JavaScript single line code, which is very easy to use~~

This paper sorts out some practical JavaScript single line code, which is very easy to use~~

Gets the value of the browser Cookie

Through document Cookie to find the cookie value

   
  1. const cookie = name =>  `; ${document.cookie}`.split( `; ${name}=`).pop().split( ';').shift();
  2.     
  3. cookie( '_ga');
  4. // Result: "GA1.2.1929736587.1601974046"

Color RGB to hex

   
  1. const rgbToHex = (r, g, b) =>  "#" + (( 1 <<  24) + (r <<  16) + (g <<  8) + b).toString( 16).slice( 1);
  2.     
  3. rgbToHex( 0,  51,  255); 
  4. // Result: #0033ff

copy to clipboard

With navigator clipboard. Writetext can easily copy the text to the clipboard

The specification requires that you use the Permissions API to obtain clipboard write permission before writing to the clipboard. However, the specific requirements of different browsers are different, because this is a new API. For more information, see compatibility table and Clipboard availability in Clipboard.

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

Check whether the date is legal

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

   
  1. const isDateValid = (...val) => !Number.isNaN( new Date(...val).valueOf());
  2.     
  3. isDateValid( "December 17, 1995 03:24:00");
  4. // Result: true

What day of the year is the lookup date

   
  1. const dayOfYear = (date) =>
  2.       Math.floor((date -  new Date(date.getFullYear(),  0,  0)) /  1000 /  60 /  60 /  24);
  3.     
  4. dayOfYear( new Date());
  5. // Result: 272

English string initial capital

Javascript does not have a built-in capital function, so we can use the following code.

   
  1. const capitalize = str => str.charAt( 0).toUpperCase() + str.slice( 1)
  2.     
  3. capitalize( "follow for more")
  4. // Result: Follow for more

Calculate the number of days between two dates

   
  1. const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) /  86400000)
  2.     
  3. dayDif( new Date( "2020-10-21"),  new Date( "2021-10-22"))
  4. // Result: 366

Clear all cookies

By using document Cookies by accessing cookies and clearing them, you can easily clear all cookies stored in web pages.

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

Generate random hex color

You can use math The random and padEnd properties generate random hexadecimal colors.

   
  1. const randomHex = () =>  `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
  2.     
  3.  console.log(randomHex());
  4. // Result: #92b008

Array de duplication

You can easily delete duplicates using Set in JavaScript

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

Get query parameters from URL

You can pass window Location or original url goole com? Search = easy & page = 3 easily retrieve query parameters from URLs

   
  1. const getParameters = (URL) => {
  2.   URL = JSON.parse(
  3.      '{"' +
  4.       decodeURI(URL.split( "?")[ 1])
  5.         .replace(/ "/g, '\\" ')
  6.         .replace(/&/g, ' "," ')
  7.         .replace(/=/g, ' ":" ') +
  8.       ' "}'
  9.   );
  10.   return JSON.stringify(URL);
  11. };
  12. getParameters(window.location);
  13. // Result: { search : "easy ", page : 3 }

Or more simply:

   
  1. Object.fromEntries( new URLSearchParams(window.location.search))
  2. // Result: { search : "easy", page : 3 }

Time processing

We can record the time in hour::minutes::seconds format from a given date.

   
  1. const timeFromDate = date => date.toTimeString().slice( 0,  8);
  2.     
  3. console.log(timeFromDate( new Date( 2021,  0,  10,  17,  30,  0))); 
  4. // Result: "17:30:00"

Is the check number odd or even

   
  1. const isEven = num => num %  2 ===  0;
  2.     
  3. console.log(isEven( 2)); 
  4. // Result: True

Average the numbers

Use the reduce method to find the average value between multiple numbers.

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

Back to the top

You can use window The scrollto (0, 0) method automatically scrolls to the top. Set both x and y to 0.

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

Flip string

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

   
  1. const reverse = str => str.split( '').reverse().join( '');
  2.     
  3. reverse( 'hello world');     
  4. // Result: 'dlrow olleh'

Check whether the array is empty

A line of code checks whether the array is empty and returns true or false

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

Gets the text selected by the user

Use the built-in getSelection property to get the text selected by the user.

   
  1. const getSelectedText = () => window.getSelection().toString();
  2.     
  3. getSelectedText();

Scramble array

You can use the sort and random methods to scramble arrays

   
  1. const shuffleArray = (arr) => arr.sort(() =>  0.5 - Math.random());
  2.     
  3. console.log(shuffleArray([ 1,  2,  3,  4]));
  4. // Result: [ 1, 4, 3, 2 ]

Check whether the user's device is in dark mode

Use the following code to check whether the user's device is in dark mode.

   
  1. const isDarkMode = window.matchMedia && window.matchMedia( '(prefers-color-scheme: dark)').matches
  2.     
  3. console.log(isDarkMode) 
  4. // Result: True or False

From: qiche mushroom cool

https://wangxiaoting.blog.csdn.net/article/details/120916063

 
  
   
  1. Previous dry goods:
  2.   26 A classic wechat applet+ 35 A set of wechat applet source code+Wechat applet collection source code download (free) dried food~~~ 2021 The latest front-end learning video~~Speed collection
  3.  Front end books-front end 290 Ben HD pdf E-book package download
  4. A little praise and watching is the greatest support❤️
@[TOC] (write custom directory title here)

Welcome to the Markdown editor

Hello! This is the welcome page displayed by the Markdown editor for the first time. If you want to learn how to use the Markdown editor, you can read this article carefully to understand the basic grammar of Markdown.

New changes

We have expanded some functions and syntax support for the Markdown editor. In addition to the standard Markdown editor functions, we have added the following new functions to help you blog with it:

  1. The new interface design will bring a new writing experience;
  2. Set your favorite code highlight style in the creation center, and Markdown will display the selected highlight style of code slice display;
  3. The picture drag function is added. You can drag local pictures directly to the editing area for direct display;
  4. New KaTeX mathematical formula syntax;
  5. Added mermaid syntax supporting Gantt chart 1 Function;
  6. The function of multi screen editing Markdown article is added;
  7. Functions such as focus writing mode, preview mode, concise writing mode and synchronous wheel setting in left and right areas are added. The function button is located between the editing area and preview area;
  8. Added check list function.

Function shortcut

Undo: Ctrl/Command + Z
Redo: Ctrl/Command + Y
Bold: Ctrl/Command + B
Italic: Ctrl/Command + I
Title: Ctrl/Command + Shift + H
Unordered list: Ctrl/Command + Shift + U
Ordered list: Ctrl/Command + Shift + O
Checklist: Ctrl/Command + Shift + C
Insert code: Ctrl/Command + Shift + K
Insert link: Ctrl/Command + Shift + L
Insert picture: Ctrl/Command + Shift + G
Find: Ctrl/Command + F
Replace: Ctrl/Command + G

Creating a reasonable title is helpful to the generation of the directory

Directly input once #, and press space to generate level 1 title.
After entering twice #, and pressing space, a level 2 title will be generated.
By analogy, we support level 6 titles. It helps to generate a perfect directory after using TOC syntax.

How to change the style of text

Emphasize text emphasize text

Bold text bold text

Tag text

Delete text

Reference text

H2O is a liquid.

210 the result is 1024

Insert links and pictures

Link: link.

Picture:

Pictures with dimensions:

Centered picture:

Centered and sized picture:

Of course, in order to make users more convenient, we have added the image drag function.

How to insert a beautiful piece of code

go Blog settings Page, select a code slice highlighting style you like, and the same highlighted code slice is shown below

// An highlighted block
var foo = 'bar';

Generate a list that suits you

  • project
    • project
      • project
  1. Item 1
  2. Item 2
  3. Item 3
  • Planning tasks
  • Complete the task

Create a table

A simple table is created as follows:

projectValue
computer$1600
mobile phone$12
catheter$1

The setting content is centered, left and right

Use: ---------: Center
Use: --------- left
Usage -----------: right

First columnSecond columnThird column
First column text centeredThe text in the second column is on the rightThe text in the third column is left

SmartyPants

SmartyPants converts ASCII punctuation characters to "smart" printed punctuation HTML entities. For example:

TYPEASCIIHTML
Single backticks'Isn't this fun?''Isn't this fun?'
Quotes"Isn't this fun?""Isn't this fun?"
Dashes-- is en-dash, --- is em-dash– is en-dash, — is em-dash

Create a custom list

Markdown Text-to- HTML conversion tool Authors John Luke

How to create a footnote

A text with footnotes. 2

Annotations are also essential

Markdown converts text to HTML.

KaTeX mathematical formula

You can render LaTeX mathematical expressions using KaTeX:

Gamma formula display Γ ( n ) = ( n − 1 ) ! ∀ n ∈ N \Gamma(n) = (n-1)!\quad\forall n\in\mathbb N Γ (n)=(n−1)! ∀ N ∈ N is through Euler integral

Γ ( z ) = ∫ 0 ∞ t z − 1 e − t d t   . \Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,. Γ(z)=∫0∞​tz−1e−tdt.

You can find more information about LaTeX mathematical expressions here.

New Gantt chart features to enrich your articles

  • For Gantt chart syntax, refer to here,

UML diagram

UML diagrams can be used for rendering. Mermaid . For example, a sequence diagram is generated as follows:

This will produce a flowchart.:

  • For Mermaid syntax, see here,

FLowchart

We will still support the flowchart of flowchart:

  • For Flowchart syntax, refer to here.

Export and import

export

If you want to try this editor, you can edit it at will in this article. When you have finished writing an article, find the article export in the upper toolbar to generate an article md file or html file for local saving.

Import

If you want to load an article you wrote md file. In the upper toolbar, you can select the import function to import the file with the corresponding extension,
Continue your creation.

  1. mermaid syntax description ↩︎

  2. Explanation of footnotes ↩︎

Keywords: Javascript Front-end

Added by bemoi on Mon, 13 Dec 2021 10:57:53 +0200