简体   繁体   English

如何使用JavaScript在网页上运行正则表达式

[英]How to run regex on webpage with javascript

I'm trying to make a bit of a crude ad-blocker with javascript The code I currently have: 我正在尝试用javascript制作粗略的广告拦截器,目前我拥有的代码是:

var pattern = '<iframe(.*?)</iframe>|<object(.*?)</object>';

if (document.body.parentNode.innerHTML.match(pattern)) 
{
    document.body.parentNode.innerHTML =
        document.body.parentNode.innerHTML.replace(pattern, '<b>AD BLOCKED</b>');
}

The problem is that the page reloads. 问题是页面重新加载。 Is there a way I can stop the page from reloading? 有什么方法可以阻止页面重新加载? (My main target is adsense) (我的主要目标是adsense)

This does not seem right, since you're just wanting to replace the html on the page. 这似乎不对,因为您只想替换页面上的html。 I can't imagine what that will do. 我无法想象会怎样。 To answer your Regex question, though, try this. 但是,要回答您的Regex问题,请尝试此操作。

var pattern = /<iframe.*<\/iframe>/gi;
document.body.innerHTML = 
    document.body.innerHTML.replace(pattern, '<strong>bye iframe</strong>');

replace() will swap out all the matches found by the RegExp with the second parameter. replace()将用第二个参数replace() RegExp找到的所有匹配项。

/<iframe.*<\\/iframe>/ is a regular expression matching anything within iframe tags. /<iframe.*<\\/iframe>/是匹配iframe广告代码中任何内容的正则表达式 gi modifies the regex telling it to be global and case-insensitive. gi修改了正则表达式,告诉它​​是全局的并且不区分大小写。

Again, you will probably have some unexpected behavior rewriting the innerHTML of the body, so I'd rethink your approach. 同样,您可能会有一些意想不到的行为来重写主体的innerHTML,所以我会重新考虑您的方法。 Perhaps you could use jQuery to find the tags you don't want and hide or remove them. 也许您可以使用jQuery查找不需要的标签,然后隐藏或删除它们。 ( example here ) 这里的例子

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

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