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 understand JavaScript Advanced regular expressions

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how to understand JavaScript high-level regular expressions, and the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

JavaScript advanced regular expression 1. Overview of regular expressions 1.1 what is a regular expression

A regular expression (Regular Expression) is a pattern that matches a combination of characters in a string. In JavaScript, regular expressions are also objects.

Regular tables are often used to retrieve and replace text that conforms to certain patterns (rules), such as validation forms: user name forms can only enter English letters, numbers, or underscores, and nicknames can enter Chinese (matching) in the input field. In addition, regular expressions are often used to filter out some sensitive words in the page content (substitution), or to get the specific part we want from the string (extraction), and so on.

Regular expressions are also used in other languages, and at this stage we are mainly using JavaScript regular expressions to complete form validation.

1.2 characteristics of regular expressions

Very flexible, logical and functional.

You can quickly achieve complex control of strings in a very simple way.

For people who have just come into contact, it is more obscure. For example: ^\ w + ([- +.]\ w +) * @\ w + ([-.]\ w +) *.\ w + ([-.]\ w +) * $

The actual development is generally to directly copy the written regular expressions. However, it is required to use regular expressions and modify them according to the actual situation. For example, the user name: / ^ [a-z0-9 percent -] {3pr 16} $/

two。 The use of regular expressions in js 2.1 the creation of regular expressions

In JavaScript, you can create a regular expression in two ways.

Method 1: create by calling the constructor of the RegExp object

Var regexp = new RegExp (/ 123 /); console.log (regexp)

Method 2: use literals to create regular expressions

Var rg = / 123Universe 2.2 Test regular expression

The test () regular object method, which is used to detect whether a string conforms to the rule, returns true or false, whose argument is a test string.

Var rg = / 123 Compact console.log (rg.test (123)); / / whether 123 occurs in matching characters will result in trueconsole.log (rg.test ('abc')); / / whether 123 will not appear in matching characters will result in false

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-gN4RwCa1-1640762098190) (images/img4.png)]

3. Special characters in regular expressions 3.1 composition of regular expressions

A regular expression can consist of simple characters, such as / abc/, or a combination of simple and special characters, such as / ab*c/. Special characters, also known as metacharacters, are special symbols with special meaning in regular expressions, such as ^, $, +, and so on.

3.2 the boundary character indicates that ^ represents the text that matches the beginning of the line (with whom) $represents the text that matches the end of the line (with whom it ends)

If ^ and $are together, it must be an exact match.

Var rg = / abc/; / / regular expressions do not require quotation marks, whether numeric or string / abc/. As long as the string contains abc, it returns trueconsole.log (rg.test ('abc')); console.log (rg.test (' abcd')); console.log (rg.test ('aabcd')) Console.log ('- -'); var reg = / ^ abc/;console.log (reg.test ('abc')); / / trueconsole.log (reg.test (' abcd')); / / trueconsole.log (reg.test ('aabcd')); / / falseconsole.log ('--') Var reg1 = / ^ abc$/; / / exact matching requirement must be an abc string to meet the specification console.log (reg1.test ('abc')); / / trueconsole.log (reg1.test (' abcd')); / / falseconsole.log (reg1.test ('aabcd')); / / falseconsole.log (reg1.test (' abcabc')); / / false3.3 character class

The character class indicates that there is a series of characters to choose from, as long as it matches one of them. All characters to choose from are placed in square brackets.

3.3.1 [] square brackets

Indicates that there are a series of characters to choose from, as long as one of them is matched.

Var rg = / [abc] /; / / return trueconsole.log (rg.test ('andy')) as long as it contains an or b or c; / / trueconsole.log (rg.test (' baby')); / / trueconsole.log (rg.test ('color')); / / trueconsole.log (rg.test (' red')); / / falsevar rg1 = / ^ [abc] $/ / / choose either an or b or c to return trueconsole.log (rg1.test ('aa')); / / falseconsole.log (rg1.test (' a')); / / trueconsole.log (rg1.test ('b')); / / trueconsole.log (rg1.test ('c')); / / trueconsole.log (rg1.test ('abc')) / / true----var reg = / ^ [amurz] $/ / 26 English letters any one of the letters returns true- to indicate Is the range a to z console.log (reg.test ('a')) / / trueconsole.log (reg.test ('z')); / / trueconsole.log (reg.test ('A')) / / false----// character combination var reg1 = / ^ [a-zA-Z0-9] $/ / / 26 English letters (both uppercase and lowercase) any letter returns true-/ / inside the square brackets plus ^ to indicate inversion Returns false as long as it contains characters in square brackets. Var reg2 = / ^ [^ a-zA-Z0-9] $/; console.log (reg2.test ('a')); / / falseconsole.log (reg2.test ('B')); / / falseconsole.log (reg2.test (8)); / / falseconsole.log (reg2.test ('!')); / / true

3.3.2 quantifier

The quantifier is used to set the number of times a pattern occurs.

Quantifier description * repeat 0 or more times + repeat 1 or more times? Repeat 0 or 1 times {n} repeat n times {n,} repeat n times or more {nMagne m} repeat n to m times

3.3.3 user name form validation

Functional requirements:

1. If the user name is entered legally, the following message is: the user name is legal and the color is green

2 if the user name is entered illegally, the following prompt message is: the user name does not conform to the specification and the color is red

Analysis:

The user name can only be composed of letters, numbers, underscores or dashes, and the length of the user name is 6-16 digits.

First of all, prepare this regular expression pattern / $[a-zA-Z0-9 mae _] {6pr 16} ^ /

Validation begins when the form loses focus.

If it conforms to the regular specification, add the right class to the following span tag.

If it does not conform to the regular specification, then add the wrong class to the following span tag.

Please enter the user name / / quantifier to set the number of times a pattern occurs var reg = / ^ [a-zA-Z0-9 times -] {6jue 16} $/; / / this mode users can only enter alphanumeric underscore var uname = document.querySelector ('.uname'); var span = document.querySelector ('span') Uname.onblur = function () {if (reg.test (this.value)) {console.log ('correct'); span.className = 'right'; span [XSS _ clean] =' username format entered correctly';} else {console.log ('incorrect'); span.className = 'wrong'; span [XSS _ clean] =' incorrect username format';}}

3.3.4 Summary of parentheses

1. Braces quantifier. It indicates the number of repeats.

two。 A collection of square bracket characters. Match any character in brackets.

3. Parentheses indicate priority

3.4 predefined classes

Predefined classes refer to the shorthand of some common patterns.

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-cETagwqf-1640762098196) (images/img3.png)]

Case: verify landline number

Var reg = / ^\ d {3} -\ d {8} |\ d {4} -\ d {7} $/; var reg = / ^\ d {3pm 4} -\ d {7pm 8} $/

Form validation case

/ / Mobile number verification: / ^ 1 [3 | 4 | 5 | 7 | 8] [0-9] {9} $/; / verify that the class name of the element and the content in the element if (reg.test (this.value)) {/ / console.log ('correct'); this.nextElementSibling.className = 'success'; this.nextElementSibling' [XSS _ clean] = 'Congratulations on typing correctly';} else {/ / console.log ('incorrect') This.nextElementSibling.className = 'error'; this.nextElementSibling [XSS _ clean] =' incorrect format, please re-enter';} / / QQ number verification: / ^ [1-9]\ d {4,} $/ / / nickname verification: / ^ [\ u4e00 -\ u9fa5] {2Magazine 8} $/ / verify that the matching code in the previous step is encapsulated by encapsulating the matching code in the previous step without changing the class name of the element and the contents of the element, and then function regexp (ele, reg) {ele.onblur = function () {if (reg.test (this.value)) {/ / console.log ('correct') This.nextElementSibling.className = 'success'; this.nextElementSibling [XSS _ clean] =' Congratulations on typing correctly';} else {/ / console.log ('incorrect'); this.nextElementSibling.className = 'error'; this.nextElementSibling [XSS _ clean] =' incorrect format, please re-enter';}

/ / password verification: / ^ [a-zA-Z0-9 authentication -] {6pc16} $/

/ / enter the password again as long as it matches whether the password value entered last time is the same.

3.5 regular replacement replace

The replace () method implements a replacement string operation, and the parameter to be replaced can be a string or a regular expression.

Var str = 'andy and red';var newStr = str.replace (' andy', 'baby'); console.log (newStr) / / baby and red// are equivalent to andy here can be written in regular expressions var newStr2 = str.replace (/ andy/,' baby') Console.log (newStr2) / / baby and red// all replace var str = 'abcabc'var nStr = str.replace (/ a gamma' ') console.log (nStr) / / bcabc// all replace gvar nStr = str.replace (/ a gamma '') console.log (nStr) / / bc bc// ignores case ivar str = 'aAbcAba' Var newStr = str.replace (/ a Gimagol '') / / "Ha-ha-bc-b-ha-ha"

Case study: filtering sensitive words

Submit var text = document.querySelector ('textarea'); var btn = document.querySelector (' button'); var div = document.querySelector ('div'); btn.onclick = function () {div [XSS _ clean] = text.value.replace (/ passion | gay/g,' * *');} 4. Interview questions 1. How to make the event bubble first and then capture it

In the original event stream, it is captured first and then bubbles.

For the target element, if the DOM node binds two event listener functions through addEventListener, one for capture and one for bubbling, then the order in which the two events are executed is in the order in which the code was added. Therefore, first bind the bubbling function, and then bind the captured function.

For non-target elements, you can add a timer to the handler that captures the event and push the handler to the next macro task.

2. Talk about event agents

Event delegation means that the event listener is not set separately in the child node, but the event listener is set on the parent node, and then the bubbling principle is used to make each child node trigger the event.

The advantage of event delegation: Dom is operated only once, which improves the performance of the program.

It is commonly used for event listening of ul and li tags. Event listeners are generally bound to ul by event delegation mechanism.

It is also suitable for the binding of dynamic elements, and newly added child elements do not need to add event handlers separately.

(1) do you know about event agents? what are the benefits of doing so?

Event agent / event delegate: taking advantage of event bubbling, you can manage a certain type of event by specifying only one event handler. In short: event broker means that we add the event to the parent node of the event to be added, and delegate the event to the parent node to trigger the handler function, which is usually used when a large number of sibling elements need to add the same kind of event. For example, if you need to add a click event to each list item in a dynamic list, you can use the event broker to judge the specific elements by judging the e.target.nodeName. The advantage of this is that the event binding is reduced, the colleague's dynamic DOM structure can still listen, and the event agent occurs in the bubbling phase.

(2) event delegation and bubbling principle:

Event delegation is realized by using the running mechanism of the bubbling phase, that is, delegating the function of one element responding to events to another element, usually delegating the events of a group of elements to its parent element.

The advantage of delegation is to reduce memory consumption and save efficiency by dynamically binding events.

Event bubbling, that is, after the event of the element itself is triggered, if the parent element has the same event, such as the onclick event, then the trigger state of the element itself will be passed, that is, to the parent element, the same event of the parent element will also be triggered outward according to the nesting relationship until document/window, and the bubbling process ends.

(3) the practical application of event agent in the capture phase:

You can prevent events from propagating to child elements at the parent element level, or you can perform certain actions on behalf of child elements.

On how to understand JavaScript high-level regular expressions to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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