我有一个带有一些文本的文本区域(假设上面写着 THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG)。当我按下一个按钮时,文本区域的内容发生变化,用另一个词(例如“RED”)替换单词“BROWN”
<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>
代码似乎不起作用。我试过查看函数是否正确缩放以及变量是否为字符串。
编辑: 该函数现在显示为:
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;
}
通过警报,我注意到 newText 与原始文本没有变化。 textElem.replace 有问题吗?
最佳答案
你做错了。
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
This method does not change the String object it is called on. It simply returns a new 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
因此你应该在 newText 上调用 replace 方法并赋值给它自己,如下所示
var newText = textElem.replace("BROWN", "RED");
newText = newText.replace("FOX", "RABBIT");//replace and assign to the same string
关于javascript - 在 javascript 中使用 string.replace() 来更改文本区域的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28320971/