You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript替换pre标签文本块中的指定变量而非全量替换?

解决pre标签占位符替换问题

你当前的代码直接用输入内容覆盖了pre标签的全部内容,要实现只替换指定占位符,只需要先获取pre标签的原始文本,再替换其中的USERNAME即可,修改后的代码如下:

<input type="text" id="myText" value="USERNAME">
<p>Enter your username above</p>
<button onclick="myFunction()">Try it</button>
<br>
<pre style="color: #000; background: #cccccc; padding:10px; display: inline-flex" id="demo">Hello USERNAME, welcome!</pre>

<script>
function myFunction() {
  // 获取用户输入的内容
  var username = document.getElementById("myText").value;
  // 获取pre标签的原始文本
  var originalText = document.getElementById("demo").textContent;
  // 替换占位符,重新赋值
  document.getElementById("demo").textContent = originalText.replace('USERNAME', username);
}
</script>

关键说明:

  • 使用textContent获取pre标签的文本内容,相比innerHTML更安全,避免误解析HTML内容
  • 字符串的replace()方法可以精准替换指定的占位符文本
  • 如果需要支持多次替换(比如文本里有多个USERNAME),可以使用正则表达式:originalText.replace(/USERNAME/g, username),g表示全局匹配

内容的提问来源于stack exchange,提问作者seba1685

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:22:53