使用jQuery替换字母

可疑蘑菇

我正在制作一个书签,将所有字母(例如“ R”)更改为其他字母(例如“ W”),或者可能替换整个单词。我尝试使用以下代码,但是它使网站混乱,并在元素中显示了元素。

javascript: $("body").text($("body").text().replace("r", "w"));

对此有解决方案吗?

对于那些想知道我将用它做什么的人,我正在尝试编写一个可以解决这个问题的代码:

您好,我叫Jonathan Grasswell,我想提出一个关于拖拉机的新主意。

变成这个:

嘿,我的外婆是乔纳西恩·格怀斯韦(Jonnyathyan Gwyassweww),我想为一个新的想法而生。

基本上是“ OWOfier”。另外,是否可以在一段时间后20%的时间插入随机图释?

罗科·C·布尔扬

如果已包含HTML内容,则为BODY。您的问题就在这里$("body").text($,因为.text(您在说:“使正文成为文本:”丢失整个标记。
您应该改为遍历3Node.TEXT_NODE)的每个NodeType,或者使用TreeWalker API

const body = document.body; // Or whatever more specific element you desire
const repl = { // Your replacements:
  "l"   : "w",
  "L"   : "W",
  "r"   : "w",
  "R"   : "W",
  "\\." : ". :)" // Remember, escape RegExp special characters to treat them as literals
};

const treeWalker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);

while (treeWalker.nextNode()) {
  const Node = treeWalker.currentNode; // PS: Node.nodeType is always 3 
  Object.keys(repl).forEach(key => {
    Node.nodeValue = Node.nodeValue.replace(new RegExp(key, "g"), repl[key]);
  });
}
.hello, .ll {color: BURLYWOOD;} /* "l"s of "class" and "hello" will stay intact */
<h1 class="hello">Hello,</h1>
<p>
  my name is <b class="ll">Long Island</b>, 
  and I would like to propose a new idea. For a clock. LOL
</p>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章