替换 html5 中文本框中的输出文本

Replace output text from textbox in html5

本文关键字:文本 输出 中文 替换 html5      更新时间:2023-09-26

如何替换html5中的输出文本。

例如,用户输入以下文本:我的名字是托尼。

我想将输出文本:"Toni"替换为 Ani,例如,输出变为:"我的名字是 Ani"。

这是我的代码:

<title>textBoxes.html</title>
 <script type = "text/javascript">
  // from textBoxes.html
  function repleace(){
  var txtName = document.getElementById("txtName");
  var txtOutput = document.getElementById("txtOutput");
  var name = txtName.value;
  if(name == "toni"){
  name = "ani";
  }
  txtOutput.value = name;
  }
 </script>
 <link rel = "stylesheet"
   type = "text/css"
   href = "textBoxes.css" />
 </head>
 <body>
 <h1>Text Box Input and Output</h1>
 <form action = "">
  <fieldset>
  <label>Type your name: </label>
  <input type = "text"
    id = "txtName" />
  <input type = "button"
    value = "GO"
    onclick = "repleace()"/>
  <input type = "text"
    id = "txtOutput" />
  </fieldset>
 </form>
 </body>
</html>

这段代码只是在我输入文本时替换文本:Toni,但是当我输入时:我的名字是 Toni。无法替换文本,托尼。

使用替换函数。

name.replace("toni", "Ani");

看看 Javascript 内置的函数替换:

http://www.w3schools.com/jsref/jsref_replace.asp

这将搜索字符串,并且仅将匹配的部分替换为新部分。

解释为什么你的代码不起作用:

您正在检查文本框值是否等于 toni,如果是,则用 ani 替换整个字符串。