11.正则表达式的一些简单应用

1.匹配11位手机号,开头字母位1

^1\d{10}$

2.匹配姓名,中文3-6位

[\u4e00-\u9fa5]{3,6}

3.匹配密码,必须是6-16位的字符,只能包含数字、字母、下划线:

$\w{6-16}^

4.匹配邮箱

^\w+@\w+(\.\w+){1,2}

5.匹配座机号

^\d{1,3}-\d{4,8}$

6.匹配一个正数

^\d+(\.\d+)?$

7.匹配一个小数

^-?\d+\.\d+

8.匹配一个整数

^-?\d+$

 

9.写一个正则表达式,去匹配一个字符串,得到匹配的次数,和匹配的结果

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var reg = /\d{3}/g;
        var s = "1234a;sdfja;sd234lkfjasldkfj";
        var n = 0;
        while(result = reg.exec(s)){
            n++;
            console.log(result[0]);
        }
        console.log(`匹配${n}次`);
    </script>
</body>

</html>
index.html

10.得到一个字符串中中文字符的数量:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var reg = /[\u4e00-\u9fa5]/g;
        var s = "1234a;s水电费234lkfjasldkfj";
        var n = 0;
        while(reg.test(s)){
            n++;
        }
        console.log(n);
    </script>
</body>

</html>
index.html

11.过滤敏感词,将一个字符串中出现的敏感词替换为3个星号:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var senWords = ["小明", "小红", "小王"];
        //将字符串中敏感词汇替换为指定的字符串
        function filterSensitiveWords(s, repStr){
            var reg = new RegExp(`(${senWords.join("|")})+`,"g");
            return s.replace(reg, repStr);
        }
        console.log(filterSensitiveWords("小明小红小王三个人去上学,课堂上小明调皮捣蛋,小红认真听课,小王在发呆", "***"));
    </script>
</body>

</html>
index.html

12.将一串数字从后向前每三个数字用逗号隔开:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var s = "123123123";
        //不是字符边界,后面是三个数字出现1到多次直到结束,全局匹配
        var reg = /\B(?=(\d{3})+$)/g;
        console.log(s.replace(reg, ","));
    </script>
</body>

</html>
index.html

结果展示:

 

 13.判断密码强度,要求密码中必须出现小写字母、大写字母、数字、特殊字符(!@#_,.):

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //判断密码强度,要求密码中必须出现小写字母、大写字母、数字、特殊字符(!@#_,.)
        var s = "123asdf&AAA(";
        var reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[(!#_,.)]).{6,12}$/;
        console.log(reg.test(s));
    </script>
</body>

</html>
index.html

 

posted @ 2020-04-23 20:46  lanshanxiao  阅读(310)  评论(0编辑  收藏  举报