javascript 查找和替换字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5951801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:55:20  来源:igfitidea点击:

find and replace string

javascriptreplace

提问by sarsar

Is it possible to look at a page's source code, find a certain part and replace it with something else before the page loads? I would like to accomplish this using JavaScript so that I can use it in a Chrome extension. So something like this:

是否可以查看页面的源代码,找到某个部分并在页面加载之前将其替换为其他内容?我想使用 JavaScript 完成此操作,以便我可以在 Chrome 扩展程序中使用它。所以像这样:

Find the google.com

找到 google.com

<script type="text/javascript">
var URLgo = "http://google.com";
</script>

Replace with yahoo.com

替换为 yahoo.com

<script type="text/javascript">
var URLgo = "http://yahoo.com";
</script>

采纳答案by Pete Hamilton

<script type="text/javascript">
function replaceScript() {
    var toReplace = 'http://google.com';
    var replaceWith ='http://yahoo.com';
    document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>

Then initialise in the body tag to do on page load.

然后在 body 标签中初始化以在页面加载时执行。

<body onload="replaceScript();">

Should work fine and replace all instances in html body code.

应该可以正常工作并替换 html 正文代码中的所有实例。

If it is in an iframe with id "external_iframe" then you would modify document.body.innerHTML to be:

如果它在 ID 为“external_iframe”的 iframe 中,那么您可以将 document.body.innerHTML 修改为:

window.frames['external_iframe'].document.body.innerHTML

Although I'm not convinced you can use it for an external site.

尽管我不相信您可以将其用于外部站点。

Seems to be some info here: Javascript Iframe innerHTML

这里似乎有一些信息:Javascript Iframe innerHTML