javascript advanced(4)

Regular expression

Regular expression is an object, mainly used to match the pattern of character combinations in a string.

Features of regular expressions

  • Some sensitive words that can filter the content of the page
  • Get the specific part we want from the string.

Create regular expression

In javascript, you can create regular expressions in two ways

test() is a method of the regular expression object, used to check whether the string conforms to the rule, and the return value is true or false.4

Note: The regular expression does not need to be quoted, whether it is a string or a value type

1. Create regular expressions by means of RegExp objects

var 变量名 = new RegExp(/表达式/)

2. Create by literal

var 变量名 = /表达式/

The expression in the middle of the comment is the regular expression literal



<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>正则表达式</title>
</head>
<body>

</body>
<script>
  //1.利用RegExp对象来创建正则表达式
  let regexp = new  RegExp(/123/);
  console.log(regexp)


  //2.利用字面量的方式来创建
  let regexp2 = /123/;
  console.log(regexp2)

  //test()方法用来检验字符串参数是否符合正则表达式的规则
  console.log(regexp.test(123));
  console.log(regexp2.test(123));
</script>
</html>


Insert picture description here

Regular expression composition

A regular expression can consist of simple characters, such as /abc/, or a combination of simple and special characters, such as ^, $, +, etc.

There are many special characters, you can refer to:

Boundary character

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

Insert picture description here
If ^ and $ exist at the same time, it means an exact match

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>正则表达式之边界符</title>
</head>
<body>

</body>
<script>
    let regexp = /abc/;
    //test()方法里面的参数只要包含abc字符,即为true
    console.log(regexp.test('abc'))//true
    console.log(regexp.test('abcd'))//true
    console.log(regexp.test('abcde'))//true

    let regexp2 = /^abc/
    //test()方法里面的参数必须以abc开头,即为true
    console.log(regexp.test('abc'))//true
    console.log(regexp.test('bacd'))//false
    console.log(regexp.test('abcde'))//true

    let regexp3 = /^abc$/
    //test()方法里面的参数必须是abc,即为true
    console.log(regexp.test('abc'))//true
    console.log(regexp.test('bacd'))//false

</script>
</html>



Insert picture description here

Character class

[]: Indicates that there are a series of characters to choose from, as long as it matches one of them.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>正则表达式之字符类</title>
</head>
<body>

</body>
<script>
    let regexp = /[abc]/ //只需包含a或b或c的字符 返回值即可true
    console.log(regexp.test('name'));
    console.log(regexp.test('body'));
    console.log(regexp.test('chinese'));
    console.log('-----------------------------------')
    
    
    
    let regexp2 = /^[abc]$/ //三选一,只能是a或b或c中的任意字符,返回值为true.
    console.log(regexp2.test('a'));
    console.log(regexp2.test('b'));
    console.log(regexp2.test('c'));
    console.log(regexp2.test('d'));//false
    console.log('-----------------------------------')
    
    
    

    let regexp3 = /^[a-z]$/ //多选一,只能是26个小写字母中任意一个字符,返回值为true.
    console.log(regexp3.test('a'));
    console.log(regexp3.test('b'));
    console.log(regexp3.test('c'));
    console.log(regexp3.test('d'));
    console.log('-----------------------------------')
    
    
    

    let regexp4 = /^[a-zA-Z0-9_-]$/ //多选一,只要是26个小写字母或26个大写字母或0-9和_-中任意一个字符,返回值为true.
    console.log(regexp4.test('A'));
    console.log(regexp4.test('b'));
    console.log(regexp4.test('0'));
    console.log(regexp4.test('!')); //false
    console.log('-----------------------------------')
    
    
    


    let regexp5 = /^[^a-zA-Z0-9_-]$/ //多选一,[]里面的^是取反的意思,只要不是[]里面的字符 都为true
    console.log(regexp5.test('A'));
    console.log(regexp5.test('b'));
    console.log(regexp5.test('0'));
    console.log(regexp5.test('!')); //true
    console.log('-----------------------------------')
    

</script>
</html>


Insert picture description here

quantifier

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


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>正则表达式之量词</title>
    </head>
    <body>

    </body>
    <!--量词符用来设定某个模式出现的次数-->
    <script>
        let regexp = /^a$/
        console.log(regexp.test('a'))
        console.log(regexp.test('aa')) //false
        console.log('----------------------------------------------')



        let regexp1 = /^a*$/ // *相当>=0,,可以出现0次或多次
        console.log(regexp1.test('a'))
        console.log(regexp1.test('aa'))
        console.log('----------------------------------------------')


        let regexp2 = /^a+$/ // +相当>=1,,可以出现1次或多次
        console.log(regexp2.test('')) //false
        console.log(regexp2.test('a'))
        console.log(regexp2.test('aa'))
        console.log('----------------------------------------------')



        let regexp3 = /^a?$/ // ?相当0|| 1次,
        console.log(regexp3.test(''))
        console.log(regexp3.test('a'))
        console.log(regexp3.test('aa')) //false
        console.log('----------------------------------------------')


        let regexp4 = /^a{3}$/ // {3}可以出现3次
        console.log(regexp4.test('')) //false
        console.log(regexp4.test('a')) //false
        console.log(regexp4.test('aaa'))
        console.log('----------------------------------------------')



        let regexp5 = /^a{3,}$/ // {3,}可以出现3次或大于3次
        console.log(regexp5.test('')) //false
        console.log(regexp5.test('aaa'))
        console.log(regexp5.test('aaaaaa'))
        console.log('----------------------------------------------')


        let regexp6 = /^a{3,16}$/ // {3,16}可以出现3到16次
        console.log(regexp6.test('')) //false
        console.log(regexp6.test('aaa'))
        console.log(regexp6.test('aaaaaaaaaaaaaa'))
        console.log('----------------------------------------------')
    </script>
</html>





Insert picture description here

Extension of quantifiers


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>正则表达式之量词</title>
    </head>
    <body>

    </body>
    <script>
        let regrxp = /^[a-zA-Z0-9_-]{6,16}$/; //输入的自述为6~16位之间 且正则表达式里面的匹配字符要完全符合
        console.log(regrxp.test('a'))//false
        console.log(regrxp.test('andy2020'))
        console.log(regrxp.test('andy202020'))
        console.log(regrxp.test('YaoZiMo'))
    </script>
</html>


Insert picture description here

Form validation of regular expressions

Core idea

1. The user name can only be composed of English letters, numbers, underscores or dashes, and the length of the user name is 6 to 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 meet the regular specification, let the span tag add the wrong class.


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>正则表达式之表单验证</title>
        <style>
            * {
            margin: 0;
            padding: 0;
        }
        span {
            color: #aaa;
            font-size: 14px;
        }
        .right {
            color:green;
        }
        .wrong {
            color: red;
        }
    </style>
    <body>
        <input type="text" class="ipt"> <span>请输入用户名</span>

    </body>
    <script>
        //1.获取元素
        var ipt = document.querySelector('.ipt')
        var span = document.querySelector('span')

        //2.正则表达式的匹配规则
        let regrxp = /^[a-zA-Z0-9_-]{6,16}$/;
        //3.设置鼠标失去焦点事件
        ipt.onblur = function() {
            if (regrxp.test(ipt.value)) {
                span.className = 'right'
                span.innerHTML = '用户输入的用户名格式正确'
            } else {
                span.className = 'wrong'
                span.innerHTML = '用户输入的用户名的格式不正确'
            }

        }
    </script>
</html>



Insert picture description here

Bracket summary

Braces: quantifiers, which indicate the number of matches

Brackets: a collection of characters. Match any character in square brackets

Parentheses: indicate priority

Online test: https://c.runoob.com/

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>正则表达式之括号总结</title>
</head>

<body>

</body>
<script>
    // 中括号:字符集合,匹配方括号里面的任意字符
    var ragExp = /^[abc]$/
    console.log(ragExp.test('a'));
    console.log(ragExp.test('b'));
    console.log(ragExp.test('c'));

    // 大括号 设定模式的匹配次数
    var ragExp1 = /^abc{3}$/
    console.log(ragExp1.test('a')); //false
    console.log(ragExp1.test('b')); //false
    console.log(ragExp1.test('abccc'));

    // 小括号 表示优先级
    var ragExp2 = /^(abc){3}$/
    console.log(ragExp2.test('a')); //false
    console.log(ragExp2.test('b')); //false
    console.log(ragExp2.test('abcabcabc'));//true
</script>

</html>





Insert picture description here

Predefined class

Predefined classes refer to shorthands for some common patterns

Insert picture description here

Landline number verification

Landline number verification: Two formats for national landline numbers: 010-12345678 or 0530-1234567


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>正则表达式之座机号码验证</title>
</head>
<body>
</body>
<script>
    // 座机号码验证: 全国座机号码  两种格式:   010-12345678 或者 0530-1234567
 var regExp = /^d{3,4}-d{7,8}$/
</script>
</html>


Form

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>正则表达式之表单验证</title>
    <style>
        body {
            background-color: rgba(0, 0, 0, 0.5);
        }

        .nav {
            list-style: none;
            width: 600px;
            padding: 20px;
            margin: 200px auto;
            border: 1px solid black;

        }

        .nav li {
            margin-bottom: 20px;
        }

        lable {
            display: inline-block;
            width: 80px;
        }
        span {
            margin-left:20px;
        }
        input[type='submit'] {
            margin-left: 96px;
            margin-right: 50px;
        }
        .right {
            color: green;
        }
        .wrong {
            color: red;
        }
    </style>
</head>
<body>
<form action="Yao.php"></form>
<ul class="nav">

    <li>
        <lable for="">用户名:</lable>
        <input type="text" class="user"><span></span>
    </li>

    <li>
        <lable for="">密 码:</lable>
        <input type="password" class="password"><span></span>
    </li>
    <li>
        <input type="submit" value="登陆"> <input type="reset" value="提交">
    </li>
</ul>

</body>
<script>
    var user = document.querySelector('.user')
    console.log(user)
    var password = document.querySelector('.password');
    console.log(password)
    var regexp = /^[a-zA-Z0-9_-]{6,16}$/;
    var regexp2 = /\w{3,20}$/;
    user.onblur = function() {
        if(regexp.test(user.value)){
            console.log(11);
            this.nextElementSibling.className='right'
            this.nextElementSibling.innerHTML='通过'
        }else {
            this.nextElementSibling.className='wrong'
            this.nextElementSibling.innerHTML='不通过'
        }
    }
    password.onblur = function() {
        if(regexp.test(password.value)){

            this.nextElementSibling.className='right'
            this.nextElementSibling.innerHTML='通过'
        }else {
            this.nextElementSibling.className='wrong'
            this.nextElementSibling.innerHTML='不通过'
        }
    }
</script>
</html>

Insert picture description here

Replacement in regular expressions

  • -replace replace

  • stringObject.replace(regexp/substr,replacement)

The first parameter: the string or regular expression to be replaced

The second parameter: the string to replace with

The return value is a new string that has been replaced


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>正则表达式中的替换</title>
    </head>
    <body>
        <textarea name="" id="" cols="30" rows="10"></textarea>
        <button>提交</button>
        <div></div>
    </body>
    <script>
        var text= document.querySelector('textarea')
        var bth = document.querySelector('button');
        var div = document.querySelector('div')
        bth.onclick = function(){
            div.innerHTML =text.value.replace(/大傻瓜|铁憨憨/g,'**')
        }
    </script>
</html>



Insert picture description here

Modifier

/表达式/[switch]

Switch (also called modifier) ​​according to what pattern to match. There are three values:

  • g: global match
  • i: Ignore case
  • gi: global match + ignore case

Guess you like

Origin blog.csdn.net/weixin_45419127/article/details/112777710