JavaScript Advanced 4

1. Overview of regular expressions

1.1 What is a regular expression

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 meets a certain pattern (rule), such as a verification form: only English letters, numbers or underscores can be entered in the user name form, and Chinese (matching) can be entered in the nickname input box. In addition, regular expressions are often used to filter out some sensitive words in the page content (replacement), or to obtain specific parts we want from a string (extract), etc.

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

1.2 The characteristics of regular expressions

  1. Flexibility, logic and functionality are very strong.
  2. The complex control of the character string can be quickly achieved in a very simple way.
  3. For those who are new to it, it is more obscure. For example: ^\w+([-+.]\w+) @\w+([-.]\w+) .\w+([-.]\w+)*$
  4. In actual development, you usually copy the written regular expression directly. However, it is required to use regular expressions and modify the regular expressions according to the actual situation.
  5. For example, username: / 1 {3,16}$/

2. 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 = /123/;

2.2 Test 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));//匹配字符中是否出现123  出现结果为true
console.log(rg.test('abc'));//匹配字符中是否出现123 未出现结果为false

Insert picture description here

3. Special characters in regular expressions

3.1 The composition of regular expressions

A regular expression can be composed of simple characters, such as /abc/, or a combination of simple and special characters, such as /ab*c/. Among them, special characters are also called metacharacters, which are special symbols with special meanings in regular expressions, such as ^, $, +, etc.

There are many special characters, you can refer to:

MDN

jQuery Manual: Regular Expression Section

[Regular Test Tool]( <http://tool.oschina.net/regex)

3.2 Boundary characters

The boundary character (position character) in the regular expression is used to indicate the position of the character, and there are mainly two characters

Boundary character Description
^ Indicates the text at the beginning of the match line (who starts with)
$ Indicates the text at the end of the matching line (ends with whom)

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

var rg = /abc/; // 正则表达式里面不需要加引号 不管是数字型还是字符串型
// /abc/ 只要包含有abc这个字符串返回的都是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$/; // 精确匹配 要求必须是 abc字符串才符合规范
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

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

3.3.1 [] Square brackets

Indicates that there are a series of characters to choose from, just match one of them.

var rg = /[abc]/; // 只要包含有a 或者 包含有b 或者包含有c 都返回为true
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]$/; // 三选一 只有是a 或者是 b  或者是c 这三个字母才返回 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个英文字母任何一个字母返回 true  - 表示的是a 到z 的范围  
console.log(reg.test('a'));//true
console.log(reg.test('z'));//true
console.log(reg.test('A'));//false
-----------------------------------------------------------------------------------
//字符组合
var reg1 = /^[a-zA-Z0-9]$/; // 26个英文字母(大写和小写都可以)任何一个字母返回 true  
------------------------------------------------------------------------------------
//取反 方括号内部加上 ^ 表示取反,只要包含方括号内的字符,都返回 false 。
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

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

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
{n,m} Repeat n to m times

3.3.3 User name form validation

Functional Requirements:

  1. If the user name is legal, the following prompt message is: The user name is legal 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
    Insert picture description here
    Insert picture description here

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 this regular expression pattern/$[a-zA-Z0-9-_]{6,16}^/
  3. Validation starts when the form loses focus.
  4. If it conforms to the regular specification, let the span tag add the right class.
  5. If it does not conform to the regular specification, let the span tag add the wrong class.
<input type="text" class="uname"> <span>请输入用户名</span>
 <script>
 //  量词是设定某个模式出现的次数
 var reg = /^[a-zA-Z0-9_-]{6,16}$/; // 这个模式用户只能输入英文字母 数字 下划线 中划线
 var uname = document.querySelector('.uname');
 var span = document.querySelector('span');
 uname.onblur = function() {
    
    
   if (reg.test(this.value)) {
    
    
   console.log('正确的');
   span.className = 'right';
   span.innerHTML = '用户名格式输入正确';
   } else {
    
    
   console.log('错误的');
   span.className = 'wrong';
   span.innerHTML = '用户名格式输入不正确';
   }
 }
</script>

3.3.4 Bracket summary

1. Braces quantifiers. The inside indicates the number of repetitions

2. Set of bracket characters. Match any character in square brackets.

3. Parentheses indicate priority

Regular expression online test

3.4 Predefined classes

Predefined classes refer to shorthands for some common patterns.
Insert picture description here

Case: Verify the landline number

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

Form validation case

//手机号验证:/^1[3|4|5|7|8][0-9]{9}$/;
//验证通过与不通过更换元素的类名与元素中的内容
 if (reg.test(this.value)) {
    
    
    // console.log('正确的');
    this.nextElementSibling.className = 'success';
    this.nextElementSibling.innerHTML = '<i class="success_icon"></i> 恭喜您输入正确';
   } else {
    
    
       // console.log('不正确');
      this.nextElementSibling.className = 'error';
      this.nextElementSibling.innerHTML = '<i class="error_icon"></i>格式不正确,请从新输入 ';
 }
//QQ号验证: /^[1-9]\d{4,}$/; 
//昵称验证:/^[\u4e00-\u9fa5]{2,8}$/
//验证通过与不通过更换元素的类名与元素中的内容 ,将上一步的匹配代码进行封装,多次调用即可
 function regexp(ele, reg) {
    
    
    ele.onblur = function() {
    
    
      if (reg.test(this.value)) {
    
    
        // console.log('正确的');
        this.nextElementSibling.className = 'success';
        this.nextElementSibling.innerHTML = '<i class="success_icon"></i> 恭喜您输入正确';
   } else {
    
    
     // console.log('不正确');
     this.nextElementSibling.className = 'error';
     this.nextElementSibling.innerHTML = '<i class="error_icon"></i> 格式不正确,请从新输入 ';
            }
        }
 };

//密码验证:/^[a-zA-Z0-9_-]{6,16}$/
//再次输入密码只需匹配与上次输入的密码值 是否一致

3.5 regular replacement replace

The replace() method can implement string replacement operations. The parameter used to replace can be a string or a regular expression.

var str = 'andy和red';
var newStr = str.replace('andy', 'baby');
console.log(newStr)//baby和red
//等同于 此处的andy可以写在正则表达式内
var newStr2 = str.replace(/andy/, 'baby');
console.log(newStr2)//baby和red
//全部替换
var str = 'abcabc'
var nStr = str.replace(/a/,'哈哈')
console.log(nStr) //哈哈bcabc
//全部替换g
var nStr = str.replace(/a/a,'哈哈')
console.log(nStr) //哈哈bc哈哈bc
//忽略大小写i
var str = 'aAbcAba';
var newStr = str.replace(/a/gi,'哈哈')//"哈哈哈哈bc哈哈b哈哈"

Case: Filtering sensitive words

<textarea name="" id="message"></textarea> <button>提交</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(/激情|gay/g, '**');
    }
</script>


  1. a-z0-9_- ↩︎

Guess you like

Origin blog.csdn.net/weixin_48116269/article/details/108203636