1. Overview of regular expressions

1.1 What is a regular expression

A Regular Expression is a pattern used to match combinations 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 a pattern (rule), such as validation forms: only letters, numbers, or underscores can be entered in the username form, and Chinese characters (match) can be entered in the nickname field. In addition, regular expressions are often used to filter out sensitive words in the content of a page (substitution), or to extract a specific part of a string that we want (extraction), etc.

Regular expressions are used in other languages as well, so in this stage we’ll focus on using JavaScript regular expressions to complete form validation.

1.2 Features of regular expressions

  1. It’s flexible, logical, and functional.
  2. Complex control of strings can be achieved quickly and in a very simple manner.
  3. For people who are new to it, it’s kind of obscure. For example: ^ \ w + (+ / – +. \ w)@\w+([-.]\w+).\w+([-.]\w+)*$
  4. In real world development, it is common to copy the regular expression directly. However, the requirement is to use regular expressions and modify the regular expressions as needed. For example, user name: /^[a-z0-9_-]{3,16}$/

2. Use regular expressions in JS

2.1 Regular expression Creation

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);
Copy the code

Method 2: Use literals to create regular expressions

 var rg = / 123 /;
Copy the code

2.2 Testing regular expressions

The test() re object method that checks if a string conforms to the rule, returns true or false, and takes the test string as an argument.

var rg = / 123 /;
console.log(rg.test(123));// Whether 123 appears in the matching character is true
console.log(rg.test('abc'));// Check whether 123 appears in the matching character
Copy the code

3. Special characters in the regular expression

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 are also called metacharacters. They are special symbols with special meanings in regular expressions, such as ^, $, and +.

Special characters are very many, you can refer to:

MDN

JQuery Manual: Regular expressions section

[Regular test tool](

3.2 the boundary character

A boundary character (position character) in a regular expression is used to indicate the position of a character. It consists of two characters

Boundary operator instructions
^ The text that matches the beginning of the line (with whom to start)
$ The text that matches the end of the line (where it ends)

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

var rg = /abc/; // Regular expressions do not require quotation marks, either numeric or string
// / ABC/returns true for any string containing ABC
console.log(rg.test('abc'));
console.log(rg.test('abcd'));
console.log(rg.test('aabcd'));
console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --');
var reg = /^abc/;
console.log(reg.test('abc')); // true
console.log(reg.test('abcd')); // true
console.log(reg.test('aabcd')); // false
console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --');
var reg1 = /^abc$/; // The exact match must be an ABC string to comply with the specification
console.log(reg1.test('abc')); // true
console.log(reg1.test('abcd')); // false
console.log(reg1.test('aabcd')); // false
console.log(reg1.test('abcabc')); // false
Copy the code

3.3 character classes

The character class represents a list of characters to choose from, and you only need to match one of them. All optional characters are enclosed in square brackets.

3.3.1 [] Square brackets

Indicates that you have a list of characters to choose from, and you only need to match one of them

var rg = /[abc]/; // Return true whenever a or b or c is included
console.log(rg.test('andy'));//true
console.log(rg.test('baby'));//true
console.log(rg.test('color'));//true
console.log(rg.test('red'));//false
var rg1 = /^[abc]$/; Return true only if the letters are a, B, or C
console.log(rg1.test('aa'));//false
console.log(rg1.test('a'));//true
console.log(rg1.test('b'));//true
console.log(rg1.test('c'));//true
console.log(rg1.test('abc'));//true
----------------------------------------------------------------------------------
var reg = /^[a-z]$/ // Each of the 26 letters returns true - representing the range from A to Z
console.log(reg.test('a'));//true
console.log(reg.test('z'));//true
console.log(reg.test('A'));//false
-----------------------------------------------------------------------------------
// Character combination
var reg1 = /^[a-zA-Z0-9]$/; // Return true for any of the 26 letters (upper and lower case)
------------------------------------------------------------------------------------
// If the square brackets inside the ^ are inverted, return false whenever the characters inside the square brackets are included.
var reg2 = /^[^a-zA-Z0-9]$/;
console.log(reg2.test('a'));//false
console.log(reg2.test('B'));//false
console.log(reg2.test(8));//false
console.log(reg2.test('! '));//true
Copy the code

3.3.2 rainfall distribution on 10-12 quantifier operator

Quantifiers are used to set the number of occurrences of a pattern.

quantifiers instructions
* Repeat 0 or more times
+ Repeat 1 or more times
? Repeat 0 or 1 times
{n} Repeated n times
{n,} Repeat n times or more
{n,m} Repeat n to m times

3.3.3 User name Form Authentication

Functional requirements:

  1. If the user name is valid, the following message is displayed: The user name is valid and the color is green
  2. If the user name is invalid, the following message is displayed: The user name is invalid and the color is red

Analysis:

  1. The username contains 6 to 16 letters, digits, underscores (_), and hyphens (-).
  2. $[a-za-z0-9 -_]{6,16}^/
  3. Validation begins when the form loses focus.
  4. If the regex specification is met, add the right class to the span tag that follows.
  5. If the regex specification is not met, add the wrong class to the span tag that follows.
<input type="text" class="uname"> <span>Please enter a user name</span>
 <script>
 // A quantifier sets the number of occurrences of a pattern
 var reg = / ^ [a - zA - Z0 - _ - 9] 6 16th} {$/; // In this mode, the user can only enter alphanumeric underscores (_) and hyphens (-)
 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.innerHTML = 'User name format entered correctly';
   } else {
   console.log('wrong');
   span.className = 'wrong';
   span.innerHTML = 'User name format entered incorrectly'; }}</script>
Copy the code

3.3.4 Parenthesis summary

1. Curly bracket quantifier. Inside is the number of repetitions

2. Set of parenthesis characters. Matches any character in square brackets.

3. The parentheses indicate the priority

Regular expression online test

3.4 Predefined Classes

Predefined classes are shorthand for some common patterns.

Example: Verify a landline number

var reg = /^\d{3}-\d{8}|\d{4}-\d{7}$/;
var reg = / ^ \ d {3, 4} - \ d {7, 8} $/;
Copy the code

Form validation cases

/ / phone number validation: / ^ 1 [3 4 5 7 | | | | 8] [0-9] {9} $/;
// Verify that the class name of the element and the contents of the element are passed or not
 if (reg.test(this.value)) {
    // console.log(' correct ');
    this.nextElementSibling.className = 'success';
    this.nextElementSibling.innerHTML = '< I class="success_icon">
       Congratulations on typing correctly ';
   } else {
       // console.log(' incorrect ');
      this.nextElementSibling.className = 'error';
      this.nextElementSibling.innerHTML = '< I class="error_icon">
       format is not correct, please retype ';
 }
Copy the code
$/ ^[1-9]\d{4,}$/;
// nickname validation :/^[\u4e00-\u9fa5]{2,8}$/
// Encapsulate the matching code of the previous step by changing the class name of the element and the content of the element with or without it
 function regexp(ele, reg) {
    ele.onblur = function() {
      if (reg.test(this.value)) {
        // console.log(' correct ');
        this.nextElementSibling.className = 'success';
        this.nextElementSibling.innerHTML = '< I class="success_icon">
       Congratulations on typing correctly ';
   } else {
     // console.log(' incorrect ');
     this.nextElementSibling.className = 'error';
     this.nextElementSibling.innerHTML = '< I class="error_icon">
       format is not correct, please retype '; }}};Copy the code
// password verification :/^[a-za-z0-9_ -]{6,16}$/
// Enter the password again only to match the password value entered last time
Copy the code

3.5 Replace replace with regular

The replace() method replaces a string with either a string or a regular expression.

var str = 'Andy and red';
var newStr = str.replace('andy'.'baby');
console.log(newStr)/ / baby, and red
// The equivalent of Andy here can be written inside a regular expression
var newStr2 = str.replace(/andy/.'baby');
console.log(newStr2)/ / baby, and red
// Replace all
var str = 'abcabc'
var nStr = str.replace(/a/.'ha ha')
console.log(nStr) / / ha bcabc
// Replace all g
var nStr = str.replace(/a/a,'ha ha')
console.log(nStr) // ha ha ha BC
// Ignore case I
var str = 'aAbcAba';
var newStr = str.replace(/a/gi.'ha ha')//" ha ha ha ha BC ha ha b ha ha"
Copy the code

Case in point: Filter sensitive words

<textarea name="" id="message"></textarea> button>
<div></div>
<script>
    var text = document.querySelector('textarea');
    var btn = document.querySelector('button');
    var div = document.querySelector('div');
    btn.onclick = function() {
    	div.innerHTML = text.value.replace(Passion | / gay/g.'* *');
    }
</script>
Copy the code