JS小练————正则表达式用法(含注释)

 本文以简单的案例介绍了正则表达式在代码中的书写与格式

文中代码及注释简单明了

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input {
            display: block;
            margin-top: 10px;
        }

        div {
            display: flex;
        }

        span {
            margin-top: 10px;
            font-size: 12px;
        }
    </style>
</head>

<body>
    <div>
        <input type="text" value="" class="ip1" id="" placeholder="账号/邮箱/手机号">
        <span class="s1">字母开头,允许5-16字节,允许字母数字下划线</span>
    </div>
    <script>
        let ip1 = document.querySelector(".ip1")
        let s1 = document.querySelector(".s1")
        let zzbds = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
        // 正则表达式
        ip1.addEventListener("blur", function () {
            // 光标移除事件
            let value = ip1.value
            // 输入内容
            let flag = zzbds.test(value)
            // 正则结果输出
            if (flag) {
                // 若真
                s1.innerHTML="账号正确"
                s1.style.backgroundColor="green"
            }
            else {
                // 若假
                s1.innerHTML="账号错误"
                s1.style.backgroundColor="red"
            }
        })
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/m0_45293340/article/details/126635963