简体   繁体   中英

Replace / Ignore JavaScript in a String

I wrote a small RSS reader with JQuery. At first theres a screen with the titles of the articles, when clicked on a title I load the content of that article. The problem is, it contains some google ads script, which will replace the content of the article and fill the whole screen with an advertisement.

The following script is what I am tying to replace or ignore:

<script type="text/javascript"><!--
google_ad_client = "ca-pub-8356817984200457";
/* ijsselmondenieuws.nl */
google_ad_slot = "9061178822";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

So I wrote a method which is supposed to remove the script by a simple replace:

 var replaceScript='<script type="text/javascript"><!--\n' +
'google_ad_client = "ca-pub-8356817984200457";\n' +
'/* ijsselmondenieuws.nl */\n' +
'google_ad_slot = "9061178822";\n' +
'google_ad_width = 468;\n' +
'google_ad_height = 60;\n' +
'//-->\n' +
'</script>\n' +
'<script type="text/javascript"\n' +
'src="http://pagead2.googlesyndication.com/pagead/show_ads.js">\n' +
'</script>';



function removeADS(ads) {
    removeAD = ads.replace(replaceScript, " ");
}

But this doesn't work, I think it's not flexible either (if it would work). When something changes in the script, the application will get stuck at the advertisement again. Is there some way to completely ignore this script while fetching the content from an RSS feed or a more flexible replacement script?

Any help is appreciated,

Thanks!

It's not very wise to parse xml/html with regex.
Use a dom parser (jquery is a beautiful one ...hint hint):

var rssContentString = '<rss version='2.0'>...',
    xmlDoc = $.parseXml(rssContentString),
    $xml = $(xmlDoc),
    helper = $('<div />'),
    result;


result = helper
    .append(
        $xml
            .find('script')
                .remove()
                .end()
    )
    .text();

UPDATE
Based on the new comments, since you get your rss content like this :

content:$.trim($(v).find("content").text())

you can modify this expression to the following :

content:$.trim($(v).find("content").find('script').remove().end().text())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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