JavaScript删除语句使用正则表达式添加新的默认语句



嗨,我正在学习java脚本。我目前正在尝试找出正则表达式。当我在文本区域字段中输入内容时,我想尝试该选项,以自动单击按钮删除在字段中输入的文本并打印regex文本,其中一些将是默认文本,并用它们的视觉显示替换HTML实体:&在&中 带有空格,"带有引号。

<!DOCTYPE html>
<html>
<body>
<textarea id="demo" name="w3review" rows="4" cols="50">
</textarea>
<br>
<button id="btnText" onclick="tipka()">click</button>
<script>
function tipka(){
let str = document.getElementById("demo").innerHTML; 
let res = str.replace(/abc/g, "Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
document.getElementById("demo").innerHTML = res;}
</script>
</body>
</html>

如果我理解问题,应该有document.getElementById("demo").value而不是document.getElementById("demo").innerHTML

<!DOCTYPE html>
<html>
<body>
<textarea id="demo" name="w3review" rows="4" cols="50">
</textarea>
<br>
<button id="btnText" onclick="tipka()">click</button>
<script>
function tipka(){
let str = document.getElementById("demo").value; 
let res = str.replace(/abc/g, "Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
document.getElementById("demo").value= res;
}
</script>
</body>
</html>

解决方案需要一些更改:

  1. tipka内部,函数应该读取textareavalue,而不是innerHTML
  2. 类似地,在替换文本时,设置textfieldvalue,而不是innerHTML

请参阅设置innerHTML与使用Javascript 设置值

以下是使用建议更改的片段:

<!DOCTYPE html>
<html>
<body>
<textarea id="demo" name="w3review" rows="4" cols="50">
</textarea>
<br>
<button id="btnText" onclick="tipka()">click</button>
<script>
function tipka() {
let str = document.getElementById("demo").value;
let res = str.replace(/abc/g, "Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
document.getElementById("demo").value = res;
}
</script>
</body>
</html>

最新更新