javascript - 在 javascript 中使用 string.replace() 来更改文本区域的内容

标签 javascript html string replace

我有一个带有一些文本的文本区域(假设上面写着 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/

相关文章:

javascript - 表单发布不接受链接

javascript - 为什么这个函数会导致错误?

html - 具有特定 CSS 的 HTML 列表的奇怪行为

从 C 中的字符串中删除子字符串的更简洁方法

javascript - jQuery 表排序器不适用于 AJAX 获取的值

javascript - 选择选项后缩小表单字段集文本

javascript - 如何使用kinetic js替换 Canvas 中的图像

html - 围绕形状的 CSS 轮廓

c# - 字符串变量 to = a textbox.text

c++ - 错误 C2065 : 'errno' : undeclared identifier in <string> in Visual Studio 2012