在javascript中使用string.replace()来更改textarea的内容

Jam*_*s S 1 html javascript string replace

我有一个带有一些文字的文本区域(假设它说的是快速的棕色狐狸在懒惰的狗身上跳过).当我按下一个按钮时,textarea的内容会改变,用另一个单词替换单词"BROWN"(例如"RED")

<textarea id="text3" >THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.</textarea>
<input type="button" value="Click here" onclick="myFunction();"/>
<script type="application/javascript">
function myFunction() {
    var textElem = document.getElementById("text3");
    var newText = textElem.replace("BROWN", "RED");
    newText = textElem.replace("FOX", "RABBIT");
    newText = textElem.replace("JUMPED", "LEAPED");
    newText = textElem.replace("LAZY", "SLEEPING");
    textElem.value = newText.value;
}
</script>
Run Code Online (Sandbox Code Playgroud)

代码似乎不起作用.我试过看看函数是否正常调用以及变量是否为字符串.

编辑:该功能现在读取:

function myFunction() {
    var textElem = document.getElementById("text3").value;
     newText = textElem.replace("BROWN", "RED");
     newText = textElem.replace("FOX", "RABBIT");
     newText = textElem.replace("JUMPED", "LEAPED");
     newText = textElem.replace("LAZY", "SLEEPING");
     alert(newText); /*I added this to see what the value of newText is*/
    textElem = newText;
}
Run Code Online (Sandbox Code Playgroud)

通过警报,我注意到newText没有改变原来的.textElem.replace有什么问题吗?

Ami*_*esh 5

你做错了.

替换()方法返回与一些或通过替换替换的图案的所有比赛的新字符串.
此方法不会更改调用它的String对象.它只返回一个新字符串.

因此,在您的情况下,您始终调用此函数,该函数textElem不会受到影响,您最终会获得上次替换的结果.

 var newText = textElem.replace("BROWN", "RED");//textElem is not changed
 newText = textElem.replace("FOX", "RABBIT");//textElem is not changed and hence you will not get the above replacement
Run Code Online (Sandbox Code Playgroud)

因此,您应该在newText上调用replace方法并像下面一样分配给它自己

 var newText = textElem.replace("BROWN", "RED");
 newText = newText.replace("FOX", "RABBIT");//replace and assign to the same string
Run Code Online (Sandbox Code Playgroud)