使用javascript在网页中查找和替换 [英] Find and replace in a webpage using javascript
问题描述
我想要做的是用JS书签/ greasemonkey脚本中的'bar'替换网页中'foo'的所有实例。我怎样才能做到这一点?我想jQuery是有效的,因为在bookmarklet和greasemonkey脚本中都包含了这些内容。
What I want to do is replace all instances of 'foo' in a webpage with 'bar' in a JS bookmarklet/greasemonkey script. How can I do this? I suppose jQuery works, as there're hacks to include those in both bookmarklets and greasemonkey scripts.
推荐答案
这个脚本遍历每个文档中的元素并用 bar
替换 foo
的每个实例。
This script iterates through each element in the document and replaces every instance of foo
with bar
.
正则表达式中的 gi
修饰符使它执行全球,不区分大小写搜索。
The gi
modifiers on the regex make it do a global, case-insensitive search.
var els = document.getElementsByTagName("*");
for(var i = 0, l = els.length; i < l; i++) {
var el = els[i];
el.innerHTML = el.innerHTML.replace(/foo/gi, 'bar');
}
您可以通过更改来定位特定的标签名称*
到你选择的标签名称(例如p
,td
)。
You can target specific tag names by changing the "*"
to the tag name of your choice (e.g. "p"
, "td"
).
这篇关于使用javascript在网页中查找和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!