Sco*_*ler 69
您可以使用以下内容替换页面正文中第一个单词:
var replaced = $("body").html().replace('-9o0-9909','The new string');
$("body").html(replaced);
Run Code Online (Sandbox Code Playgroud)
如果要替换所有出现的单词,则需要使用正则表达式并将其声明为全局/g
:
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);
Run Code Online (Sandbox Code Playgroud)
如果你想要一个班轮:
$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>'));
Run Code Online (Sandbox Code Playgroud)
您基本上将<body>
页面标记中的所有HTML都转换为字符串变量,使用replace()查找并更改找到的字符串的第一个匹配项.或者如果你想找到并替换所有出现的字符串,请在混合中引入一点正则表达式.
在这里查看演示 - 查看左上方的HTML以查看原始文本,下面的jQuery以及右下角的输出.
小智 37
像这个线程中提到的其他人一样,替换整个HTML是一个坏主意,因为它重新插入整个DOM并且可能会破坏任何其他对这些元素起作用的javascript.
相反,使用jQuery过滤器仅替换页面上的文本而不是DOM元素本身:
$('body :not(script)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('-9o0-9909','The new string');
});
Run Code Online (Sandbox Code Playgroud)
this.nodeType是我们要替换其内容的节点类型.nodeType 3是文本.请在此处查看完整列表.
ale*_*lex 13
...我有一个字符串"-9o0-9909",我想用另一个字符串替换它.
下面的代码会这样做.
var str = '-9o0-9909';
str = 'new string';
Run Code Online (Sandbox Code Playgroud)
除了笑话,用JavaScript替换文本节点并不是一件容易的事.
我写过一篇关于此的帖子:用JavaScript替换文本.
html替换的想法很好,但如果对document.body做了,页面将闪烁,广告将消失.
我的解决方案
$("*:contains('purrfect')").each(function() {
var replaced = $(this).html().replace(/purrfect/g, "purrfect");
$(this).html(replaced);
});