正则表达式替换 JavaScript

您好,这看起来很简单,但我不明白为什么第一个功能不起作用。我尝试了几种变体,但我的逻辑有问题。当我查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace时,我似乎已经正确完成了它,但它不会替换文本。在此先感谢您的帮助。

<!DOCTYPE html>

<html>

    <body>

        <p id="p1">Mr Red has a red house and a red car.</p>

        <p id="p2">Mr Red has a red house and a red car.</p>


        <button onclick="replace1()">Replace red with blue</button>

        <button onclick="replace2()">Replace red with blue too</button>

        <script>

            function replace1()

            {

                var str = document.getElementById("p1").innerHTML;

                str.replace(/red/, "blue");

                document.getElementById("p1").innerHTML = str;

            }

                function replace2()

            {

                var str = document.getElementById("p1").innerHTML;

                var rep = str.replace(/red/, "blue");

                document.getElementById("p2").innerHTML = rep;

            }

    

    </script>

    </body>

</html>


慕斯709654
浏览 110回答 1
1回答

忽然笑

在您的第一个函数中,只需将值分配给变量 str。在您的代码中更新它。&nbsp;str = str.replace(/red/, "blue");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript