简单的Javascript对html文本框转换.不能工作两次

Simple Javascript on html textbox conversion. Doesn't work twice

本文关键字:工作 两次 不能 转换 Javascript html 文本 简单      更新时间:2023-09-26

我正在使用replace方法,如果我输入"test test",只有第一个测试被转换为good,所以它将成为"good test"。我不明白为什么会发生这种事。附带的问题是,如果我要添加20个我想替换的单词,我需要创建20个不同的str。replace吗?

<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "Test" with "Good"</p>
<textarea id="firstbox"></textarea>
<textarea id="secondbox"></textarea>
<button onclick="myFunction()">Change</button>
<script>
    function myFunction() {
        var str = document.getElementById("firstbox").value.toLowerCase()
        var res = str.replace("test", "good");
        document.getElementById("secondbox").value = res;
    }
</script>
</body>
</html>

如有任何帮助,不胜感激

使用正则表达式,将"good"改为/good/g

function myFunction() {
        var str = document.getElementById("firstbox").value.toLowerCase()
        var res = str.replace(/test/g, "good");
        document.getElementById("secondbox").value = res;
    }
<p>Click the button to replace "Test" with "Good"</p>
<textarea id="firstbox"></textarea>
<textarea id="secondbox"></textarea>
<button onclick="myFunction()">Change</button>