JavaScript advanced day 04 notes

Posted by bschmitt78 on Tue, 18 Jan 2022 22:51:36 +0100

JavaScript advanced day 04 notes

1. Regular expression overview

1.1 what is a regular expression

Regular Expression is a pattern used to match character combinations in a string. In JavaScript, regular expressions are also objects.

Regular tables are usually used to retrieve and replace text that conforms to a certain pattern (rule), such as verification forms: the user name form can only enter English letters, numbers or underscores, and the nickname input box can enter Chinese (matching). In addition, regular expressions are often used to filter out some sensitive words in the page content (replacement), or get the specific part we want from the string (extraction), etc.

Other languages also use regular expressions. At this stage, we mainly use JavaScript regular expressions to complete form verification.

1.2 characteristics of regular expressions

  1. Flexibility, logic and functionality are very strong.
  2. It can quickly achieve the complex control of string in a very simple way.
  3. For people who have just come into contact, it is more obscure and difficult to understand. For example: ^ \ w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*$
  4. The actual development is generally to directly copy the written regular expression However, it is required to use regular expressions and modify them according to the actual situation For example, user name:/ [1]{3,16}$/

2. Use of regular expressions in js

2.1 creation of regular expressions

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

Method 1: create by calling the constructor of RegExp object

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

Method 2: create regular expressions with literal values

 var rg = /123/;

2.2 testing regular expressions

The test() regular object method is used to detect whether the string conforms to the rule. The object will return true or false, and its parameter is the test string.

var rg = /123/;
console.log(rg.test(123));//Whether 123 appears in the matching character, and the result is true
console.log(rg.test('abc'));//Whether 123 appears in the matching character. If it does not appear, the result is false

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 significance in regular expressions, such as ^, $, + and so on.

There are many special characters. You can refer to:

MDN

jQuery Manual: regular expressions section

[regular test tool]< http://tool.oschina.net/regex)

3.2 boundary character

The boundary character (position character) in regular expression is used to indicate the position of the character. There are mainly two characters

Boundary character explain
^ Represents the text that matches the beginning of the line (starting with who)
$ Represents the text that matches the end of the line (with whom)

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

var rg = /abc/; // Regular expressions do not need quotation marks, whether numeric or string
// /abc / as long as abc is included, the string returns true
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$/; // Exact matching requires an abc string to meet 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

3.3 character class

Character class means that there are a series of characters to choose from, as long as you match one of them. All selectable characters are placed in square brackets.

3.3.1 [] square brackets

Indicates that there are a series of characters to choose from, as long as you match one of them

var rg = /[abc]/; // It returns true as long as it contains a, b or c
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]$/; // Choose one from three. Only the letters a, b or c return true
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]$/ //26 English letters. Any letter returns true - indicating 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]$/; // 26 English letters (both uppercase and lowercase) any letter returns true  
------------------------------------------------------------------------------------
//The addition of ^ inside the inverted square brackets indicates negation. As long as the characters in the square brackets are included, false is returned.
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

3.3.2 quantifier

Quantifier is used to set the number of times a pattern appears.

classifier explain
* Repeat 0 or more times
+ Repeat 1 or more times
? Repeat 0 or 1 times
{n} Repeat n times
{n,} Repeat n or more times
{n,m} Repeat n to m times

3.3.3 user name form verification

Functional requirements:

  1. If the user name is valid, the following prompt message is: the user name is valid and the color is green
  2. If the user name input is illegal, the following prompt message is: the user name does not meet the specification, and the color is red

analysis:

  1. The user name can only be composed of English letters, numbers, underscores or dashes, and the length of the user name is 6 ~ 16 digits
  2. First, prepare the regular expression pattern / $[a-za-z0-9 -] {6,16}^/
  3. Validation begins when the form loses focus
  4. If it conforms to the regular specification, let the following span tag add the right class
  5. If it does not conform to the regular specification, let the following span tag add the wrong class
<input type="text" class="uname"> <span>enter one user name</span>
 <script>
 //  Quantifiers are used to set the number of times a pattern appears
 var reg = /^[a-zA-Z0-9_-]{6,16}$/; // In this mode, the user can only input English alphanumeric underline and underline
 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 input is correct';
   } else {
   console.log('FALSE');
   span.className = 'wrong';
   span.innerHTML = 'Incorrect user name format';
   }
 }
</script>

3.3.4 bracketed summary

1. Brace quantifier It indicates the number of repetitions

2. Bracketed character set. Matches any character in parentheses

3. Parentheses indicate priority

Regular expression online test

3.4 predefined classes

Predefined classes are shorthand for some common patterns

Case: verify landline number

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

Form validation case

//Mobile phone number verification: / ^ 1 [3 | 4 | 5 | 7 | 8] [0-9] {9} $/;
//Verify whether to replace 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.innerHTML = '<i class="success_icon"></i> Congratulations on your correct input';
   } else {
       // console.log('incorrect ');
      this.nextElementSibling.className = 'error';
      this.nextElementSibling.innerHTML = '<i class="error_icon"></i>Incorrect format,Please enter from New ';
 }
//QQ number verification: / ^ [1-9]\d{4,} $/; 
//Nickname verification: / ^ [\ u4e00-\u9fa5]{2,8}$/
//Verify whether it passes or not, replace the class name of the element and the content in the element, encapsulate the matching code in the previous step, and call it multiple times
 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"></i> Congratulations on your correct input';
   } else {
     // console.log('incorrect ');
     this.nextElementSibling.className = 'error';
     this.nextElementSibling.innerHTML = '<i class="error_icon"></i> Incorrect format,Please enter from New ';
            }
        }
 };
//Password verification: / ^ [a-za-z0-9 -]{6,16}$/
//If you enter the password again, just match whether it is consistent with the password value you entered last time

3.5 regular replace

The replace() method can implement the replace string operation, and the parameter used to replace 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
//andy, which is equivalent here, can be written in 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 ha bcabc
//Replace all g
var nStr = str.replace(/a/a,'ha-ha')
console.log(nStr) //Ha ha bc ha ha bc
//Ignore case i
var str = 'aAbcAba';
var newStr = str.replace(/a/gi,'ha-ha')//"Ha ha ha bc ha ha b ha ha"

Case: filter sensitive words

<textarea name="" id="message"></textarea> <button>Submit</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>
  1. a-z0-9_- ↩︎

Topics: Javascript