範例程式-String


把下列程式碼貼在string-sample.html上執行,可以測試 match, search, replace, split 四種函式。

<!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>String型態的函式</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>

<body>

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

    正規表示式:
    <input id="pattern" type="text" value="/\d/g"><br><br>
    比對字串:
    <textarea id="str" type="text" cols=50 rows=3>I have 123 pens and 456 pencils.</textarea><br><br>
    match結果:
    <div id="match-result" style="background:PapayaWhip "></div><br>
    search結果:
    <div id="search-result" style="background:PapayaWhip "></div><br>
    replace結果:(要代換的字串:<input type="text" id="replace-str" value="x">)
    <div id="replace-result" style="background:PapayaWhip "></div><br>
    split結果:
    <div id="split-result" style="background:PapayaWhip "></div><br>

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

        function checkRegExp(e) {
            var pattern = eval($("#pattern").val());
            var str = $("#str").val();
            var matchResult = str.match(pattern);
            var searchResult = str.search(pattern);
            var replaceResult = str.replace(pattern, $("#replace-str").val());
            var splitResult = str.split(pattern);

            console.log("正規表示式: " + pattern + "  字串: " + str);

            $("#match-result").text(matchResult);
            $("#search-result").text(searchResult);
            $("#replace-result").text(replaceResult);
            $("#split-result").text(splitResult);
        }
    </script>

</body>

</html>

results matching ""

    No results matching ""