The second stage of front-end learning (Day16)

catalogue

1. Concept:

2. Definition method:

3. Common methods:

                1.test

                2.search

                3.match

                4.replace

                5.exec

4. Common metacharacters ~ special characters

5. Connector - range

6. Qualifier quantifier

7. Locator - boundary

8. Modifier

9. Special escape character

10. Priority order

2. Greedy mode and non greedy mode

1. Greedy mode [default]

2. Non greedy mode

Case:

1. Regular expression

1. Concept:

Formula for matching a type of string with a certain pattern

2. Definition method:

Explicit definition: [constructor]

let variable name = new RegExp('regular expression pattern ')

Implicit definition: [literal]

let variable name = / regular expression pattern/

3. Common methods:

                1.test

Regular to match strings. If the matching is successful, it returns true; otherwise, it returns false

Regular. Test (string)

                2.search

Regular de matching string, if the matching is successful, the successful position will be returned, otherwise - 1 will be returned

String. Search (regular)

                3.match

Regular de matching of strings. If the matching is successful, the array with successful matching will be returned. Otherwise, null will be returned

String. Match (regular)

                4.replace

Regular de matching of strings, and successful matching strings are replaced by new strings

Str.replace (regular, new string)

                5.exec

Regular de matching of strings. If the matching is successful, an array of successful matches will be returned. index: indicates the position of the first matched character in the original string. input: indicates the original string. group: indicates the grouping object matched when grouping the junior high school command. If the matching is unsuccessful, null will be returned

Regular. Exec (string)

4. Common metacharacters ~ special characters

Metacharacterexplain
\dMatching number, equivalent to [0-9]
\DMatch non numbers, equivalent to [^ 0-9]
\wMatch letters or numbers or Chinese characters or underscores
\WMatch any character that is not a letter, number, Chinese character or underscore
\sMatch any blank character, such as space, line feed, tab, etc
\SMatch any character that is not a whitespace
(DOT)Matches any character except newline. \ n
[...]Match all characters in parentheses
[^...]Match all characters in non square brackets

5. Connector - range

Connectorexplain
[0-9]Match number, equivalent to \ d
[a-z]Match English lowercase letters
[A-Z]Match English capital letters
[0-9a-zA-Z]Match numbers or English letters

6. Qualifier quantifier

qualifierexplain
+Repeat 1 or more times
*Repeat 0 or more times (any time)
Repeat 0 times or 1 time
{n}Repeat n times
{n,}Repeat n times or more (at least N times)
{n,m}Repeat n to m times

7. Locator - boundary

        

Locatorexplain
^The character that defines the start position
$The character that defines the end position
\bA character that defines the boundary of a word (word) -- a space
\BCharacters that define non word boundaries

8. Modifier

1.g:global full-text search, do not add, stop when the first match is found

2.i:ignore case ignore case sensitivity by default

3.m:multiple lines

9. Special escape character

\ f match page feed

\ nmatch newline

\ rmatch carriage return

\ t match matching table symbol

\ v match vertical tab

\ \ match\

\ "match"

\ 'match'

                \. Match

10. Priority order

Operator or expressionexplain
\Escape character
(),(?:),(?=),[]Parentheses or square brackets
*,+,?,{n},{n,},{n,m}qualifier
^,$,\b,\BLocation and sequence
|Selector, "or" operation

2. Greedy mode and non greedy mode

1. Greedy mode [default]

The regularization engine matches characters as many times as possible

2. Non greedy mode

The regularization engine matches characters as few times as possible. You can use?, +?? etc.

Case:

1. Known mailbox string ' zhousir028@qq.com 'write regular matching. Does the mailbox string conform to the mailbox format?

Mailbox format requirements:

1. The "@" symbol must be included

2. The left and right sides of the @ symbol can be letters or numbers or combinations of letters and numbers

3. End with. com

<script>
 function test01(){
        let regs=new RegExp("[0-9a-zA-Z]+@[0-9a-zA-Z]+.com$")
        const str='wuyuling09@qq.com'
        let reg=/[0-9a-zA-Z]+@[0-9a-zA-Z]+\.com$/
        let bool=reg.test(str)
        alert(bool)
        alert(`Constructor ${regs.test(str)}`)
    }
   test01()
</script>

         

2. Replace the word is in the string with 'are' string as follows:

                'He is a boy, This is a dog.Where is she?'

<script>
   function test05(){
        const str='He is a boy, This is a dog.Where is she?'
        let reg=/\bis\b/mg
        var str1=str.replace(reg,'are')
        alert(`str: ${str}\n str1:${str1}`)
    }
  test05()
</script>

3. Match date and time, and set mm / DD / yyyy to mm / DD / yyyy

    <script>
        const str = '2022-09-05'  //-> 09/05/2022
        const reg = /(\d{4})-(\d{2})-(\d{2})/
        let newStr = str.replace(reg,'$2/$3/$1')
        console.log(newStr)

           //Array and back reference
    </script>

4. Click element block move - motion function

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Encapsulated motion function</title>
		<style>
			* {
				padding: 0;
				margin: 0;
			}
			div {
				position: absolute;
				top: 100px;
				left: 600px;
				width: 100px;
				height: 100px;
				background-color: skyblue;
			}
            p{
                position: absolute;
                top: 300px;
                left: 600px;
                width: 80px;
                height: 80px;
                background-color: pink;
            }
		</style>
	</head>
	<body>
		<div></div>
        <p></p>

		<script>
            const divEle = document.querySelector('div')
            divEle.addEventListener('click',function(){
                move(divEle,400) 
            })

            const pEle = document.querySelector('p')
            pEle.addEventListener('click',function(){
                move(pEle,-300)
            })


            /*
              Motion function
              ele Sports element
              offset Is the total movement distance, the offset is positive to the right and negative to the left
            */
			function move(ele, offset) {
				let time = 1000 // Total time
				let rate = 50 // speed
				let distance = (offset * rate) / time // Distance per move

				//Initialize current location
				ele.style.left = window.getComputedStyle(ele).left
				let init = parseInt(ele.style.left)

				// Calculate target position
				let goal = init + offset

				const timer = setInterval(function () {
					if (parseInt(ele.style.left) == goal ||
						Math.abs(Math.abs(goal) - Math.abs(parseInt(ele.style.left))) < Math.abs(distance)
					) {
                        // If the distance between the current position and the target position is less than the moving distance, directly reach the target position
						ele.style.left = goal + 'px' 
						clearInterval(timer)
					} else {
						ele.style.left = parseInt(ele.style.left) + distance + 'px'
					}
				}, rate)
			}
		</script>
	</body>
</html>

Tags: html Javascript Front-end

Posted by rigy73 on Mon, 05 Sep 2022 22:59:21 +0530