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

What is the use of regular expressions in JavaScript

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

Share

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

This article mainly explains "what is the use of regular expressions in JavaScript". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the use of regular expressions in JavaScript".

What is a regular expression

Is a pattern used to match 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.

1. Characteristics of regular expressions

The flexibility of regular expressions.

Very logical and functional.

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

2. The use of regular expressions

1. Create a regular expression

There are usually two ways to create.

1) create by calling the constructor of the RegExp object

Var variable name = new RegExp (/ expression /)

2) create by literal quantity

Var variable name = / expression /

/ / comment the expression in the middle is the regular literal.

2. Test regular expressions

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.

RegexObj.test (str)

Where:

RegexObj-regular expressions written

Str-text to test

This means to detect whether the str text conforms to the written regular expression specification.

For example:

Given a regular expression var rg = / 123max, determine whether the string we entered conforms to the rules.

Var str = '123'var reg1 = new RegExp (/ 123 /); var reg2 = / abc/;console.log (reg1.test (str)); console.log (reg2.test (str))

The print result is

2. Special characters in regular expressions 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.

2. Boundary character

The boundary character (position character) in a regular expression is used to indicate the position of the character, which has two main characters.

The boundary symbol indicates that ^ represents the text that matches the beginning of the line $represents the text that matches the end of the line

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

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.

1. [] square bracket class

/ [abc] / .test ('andy') / / true

The following string returns true as long as it contains any character in abc.

2. Inner range character of [-] square brackets-

/ ^ [amurz] $/ .test (c') / / true

The square brackets are enclosed with-to indicate a range, which means that 26 letters from a to z are fine.

3. [^] take the reverse character ^ inside the square brackets

/ [^ abc] / .test ('andy') / / false

Adding ^ inside square brackets indicates inversion, and returns false as long as it contains characters in square brackets.

Note that it is different from the boundary character ^, which is written outside the square brackets.

4. Character combination

/ [a-z1-9] / .test ('andy') / / true

Character combinations can be used inside square brackets, which means that 26 letters from a to z and numbers from 1 to 9 are fine.

4. Quantifier

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

Quantifier means * repeat zero or more times + repeat one or more times? Repeat 0 or one {n} n times {n,} repeat n or more times {n ~ m} repeat n to m times var reg = / ^ a circle moves; / / * equals > = 0, can occur 0 or many times var reg = / ^ a circle moves; / / + equals > = 1, can occur one or more times var reg = / ^ a circle steps; / /? | equivalent to 1 | 0, var reg = / ^ a {3} $/; / / {3} means repeating a character 3 times var reg = / ^ a {3,} $/; / / {3,} is repeating a character greater than or equal to 3 times var reg = / ^ a {3pr 16} $/; / / {3pm 16} means repeating a character greater than or equal to 3 times less than 16 times.

For example, in a case of user name verification, if the user name is entered legally, the prompt message is: the user name is legal and the color is green; if the user name input is illegal, the prompt message is: the user name is illegal and the color is green.

The code is as follows:

Document .success {color:green;} .resume {color:red;} username: $(function () {var reg = / ^ [a-zA-Z0-9customers -] {6Magne 16} $/) $('.uname') .bind ('blur',function () {let str = $(this) .val (); if ($(' input'). Val = null) {$('span') .removeClass () } if (reg.test (str)) {if ($('span'). HasClass (' wrong')) $('span'). RemoveClass () $(' span') .html ('input format is correct') $('span') .addClass (' success')} else {$('span') .html (' incorrect input format'); $('span') .addClass (' wrong')})})

The display effect is as follows:

5. Summary of parentheses

Braces quantifier. It indicates the number of repeats.

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

Parentheses indicate priority

6. Predefined class

Predefined classes refer to the shorthand of some common patterns.

Method 1. Match () method in string class

The match () method: according to the regular match, all the content that meets the requirements is saved to the array after a successful match, and a false is returned if the match fails.

For example:

Var str = "It's is the shorthand of it is"; var reg1 = / it/gi;str.match (reg1); / / matching result: (2) ["It", "it"] var reg2 = / ^ it/gi;str.match (reg2); / / matching result: ["It"] var reg3 = / sgamgi; str.match (reg3) / / match result: (4) ["s", "s"] var reg4 = / s match (reg4); / / match result: ["s"] 2, search () method

The search () method: the search () method returns the position where the substring of the specified pattern first appears in the string, which is more powerful than the indexOf () method.

For example:

Var str = '123\ abc.456\ console.log (str.search ('. *')); / / output result: 0console.log (/ [\.\ *] /); / / output result: 33, split () method

Split () method: the split () method is used to split a string into an array of strings based on the specified delimiter, which does not include the delimiter.

For example:

Follow the "@" and "." in the string The two delimiters are divided.

Var str = 'test@123.com';var reg = / [@\.] /; var split_res = str.split (reg); console.log (split_res); / / output result: (3) ["test", "123", "com"]

When a string is split by regular matching, you can also specify the number of times the string is split.

Var str ='We are a family';var reg = /\ replace split_res = str.split (reg, 2); console.log (split_res); / / output result: ["We", "are"] 4, replace () method

The replace () method: the replace () method is used to replace a string, and the argument used for the operation can be a string or a regular expression.

For example: write a case of finding and replacing sensitive words (filtering Chinese characters and the word 'bad'):

Document

Content before filtering

Filter

Filtered content

Var text = document.querySelectorAll ('textarea'); console.log (text); var btn = document.querySelector (' button'); btn.onclick = function () {text [1] .value = text [0] .value.replace (/ (bad) | [\ u4e00 -\ u9fa5] / gi,'*');}

The running effect is as follows:

Thank you for your reading, the above is the content of "what is the use of regular expressions in JavaScript". After the study of this article, I believe you have a deeper understanding of the use of regular expressions in JavaScript, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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