简体   繁体   English

如何替换 HTML 页面中字符串的第一个实例?

[英]How would I replace the first instance of a string in an HTML page?

I am a technical writer and in my job we run into a lot of content reuse.我是一名技术作家,在我的工作中我们遇到了很多内容重用的情况。 It's standard to write out the first instance like "Hypertext Markup Language (HTML)" and just use HTML from then on out.写出像“超文本标记语言(HTML)”这样的第一个实例是标准的,并且从那时起只使用 HTML。 However, if I'm constantly reusing blocks of text, it is hard to do this consistently.但是,如果我经常重复使用文本块,就很难始终如一地做到这一点。 I would like to simply write the acronym every time, and on page load, replace the first instance with the complete phrase via JS.我想每次都简单地写下首字母缩略词,然后在页面加载时,通过 JS 将第一个实例替换为完整的短语。

I tried this script that I found online, but it doesn't work and generates an error in chrome developer tools (TypeError: "body".html is not a function):我尝试了这个我在网上找到的脚本,但它不起作用并在 chrome 开发人员工具中生成错误(TypeError:“body”。html 不是函数):

var replaced = ("body").html().replace('HTML', 'Hypertext Markup Language');
$("body").html(replaced);

Is this script wrong or am I missing something?这个脚本是错误的还是我遗漏了什么?

How about this:这个怎么样:

function textNodesUnder(el){
  var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(n=walk.nextNode()) a.push(n);
  return a;
}

function replaceAllInPage(oldStr, newStr) {
  textNodesUnder(document.body).forEach(node => {
    node.textContent = 
      node.textContent.replaceAll(oldStr, newStr);
  });
}

replaceAllInPage('HTML', 'Hypertext Markup Language');

textNodesUnder is by Phrogz textNodesUnder 由 Phrogz 设计

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM