範例程式-RegExp


把下列程式碼貼在regexp-sample.html上執行,可以測試 test, match 兩種函式。

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>RegExp型態的函式</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>

<body>

    <h3>RegExp型態的函式</h3>
    <hr>

    正規表示式:
    new RegExp(" <input id="pattern" type="text" value="Pen"> ","
    <input id="attributes" type="text" value="i" size="1">")<br><br>
    比對字串:
    <textarea id="str" type="text" cols=50 rows=3>I have 123 pens and 456 pencils.</textarea><br><br>
    test結果:
    <div id="test-result" style="background:PapayaWhip "></div><br>
    exec結果:
    <div id="exec-result" style="background:PapayaWhip "></div>

    <script type="text/javascript">
        $(function () {
            $("#pattern , #attributes , #str").keyup(checkRegExp);
            checkRegExp();
        });

        function checkRegExp(e) {
            var str = $("#str").val();
            var pattern;
            if($("#attributes").val()){
                pattern = new RegExp($("#pattern").val(),$("#attributes").val());
            } else {
                pattern = new RegExp($("#pattern").val());
            }
            testResult = pattern.test(str);
            execResult = pattern.exec(str);
            console.log("正規表示式: " + pattern + "  字串: " + str + "  驗證結果:" + testResult);
            console.log(execResult);
            $("#test-result").html(testResult ? "true" : "false");
            $("#exec-result").html(execResult+"<br>index:"+execResult.index+"<br>input::"+execResult.input);

        }
    </script>

</body>

</html>

results matching ""

    No results matching ""