【代码笔记】Web-JavaScript-JavaScript正则表达式

一,效果图。

二,代码。

复制代码
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>JavaScript 正则表达式</title>
</head>

<body>
    <!--search方法使用正则表达式-->
    <p>搜索字符串"w3cSchool",并显示匹配的起始位置</p>
    <button onclick="myFunction()">点我</button>
    <p id="demo"></p>
    <script>
    function myFunction() {
        var str = "Visit W3cSchool!";
        var n = str.search(/w3cSchool/i);
        document.getElementById("demo").innerHTML = n;
    }
    </script>
    <!--search方法使用字符串-->
    <p>搜索字符串 "W3cSchool", 并显示匹配的起始位置:</p>
    <button onclick="myFunction()">点我</button>
    <p id="demo1"></p>
    <script>
    function myFunction() {
        var str = "Visit W3cSchool!";
        var n = str.search("W3cSchool");
        document.getElementById("demo1").innerHTML = n;
    }
    </script>
    <!--replace方法使用正则表达式-->
    <p>替换"microsoft"为"w3cschool</p>
    <button onclick="myFunction()">点我</button>
    <p id="demo3">Please visit microsoft</p>
    <script>
    function myFunction() {
        var str = document.getElementById("demo3").innerHTML;
        var txt = str.replace(/microsoft/i, "w3cshool");
        document.getElementById("demo3").innerHTML = txt;
    }
    </script>
    <!--replace方法使用字符串-->
    <p>替换"microsoft"为"w3cschool"</p>
    <button onclick="myFunction()">点我</button>
    <p id="demo4">please visit microsoft</p>
    <script>
    function myFunction() {
        var str = document.getElementById("demo4").innerHTML;
        var txt = str.replace(/microsoft/i, "w3cschool");
        document.getElementById("demo4").innerHTML = txt;
    }
    </script>
    <!--使用 test()-->
    <script>
    var patt1 = new RegExp("e");

    document.write(patt1.test("The best things in life are free"));
    </script>
    <!--使用 exec()-->
    <script>
    var patt1 = new RegExp("e");
    document.write(patt1.exec("the best things in life are free"));
    </script>
</body>

</html>
复制代码

 

参考资料:《菜鸟教程》

posted @ 2018-12-28 09:28  花儿迎风笑  阅读(268)  评论(0编辑  收藏  举报