Javascript regex matches iframe src

If I have two iframes, how can I match one that doesn't have youtube src?

<iframe  src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-feed-pub"></iframe>
<iframe  src="http://www.youtube.com/embed/Y4MnpzG5Sqc?wmode=opaque"></iframe>
+3
source share
2 answers

Do you have all your data on one line that can contain multiple tags? In this case, you need to: 1) find each individual iframe in the line, 2) check each found iframe if you need to delete it or leave it alone. Here's the code that does this only with comments showing where each step is performed:

var string='<iframe  src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-feed-pub"></iframe><iframe  src="http://www.youtube.com/embed/Y4MnpzG5Sqc?wmode=opaque"></iframe><iframe  src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-feed-pub"></iframe><some_good_tag>TEST</some_good_tag><iframe  src="http://www.youtube.com/embed/Y4MnpzG5Sqc?wmode=opaque"></iframe>'

function filter_iframe(iframe_tag){
    // if iframe have youtube in it - return it back unchanged
    if(/src=".+youtube/.test(iframe_tag)){ return iframe_tag }
    // if not - replace it with empty string, effectively removing it
    return ''
}

// first, find each iframe in string and call function to check if you need to remove it
var filtered=string.replace(/(<iframe.*?>.*?<\/iframe>)/g, filter_iframe)

console.log(filtered)
+4
source
var a='<iframe  src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-feed-pub"></iframe><iframe  src="http://www.youtube.com/embed/Y4MnpzG5Sqc?wmode=opaque"></iframe><iframe  src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-feed-pub"></iframe><iframe  src="http://www.youtube.com/"></iframe>'

var b=a.match(/(<iframe.+?<\/iframe>)/g),l=b.length,i=0;
for(i;i<l;i++){
  if(b[i].indexOf('youtube.com')>-1){a=a.replace(b[i],'')}
}​

http://jsfiddle.net/7ykXv/

+1
source

All Articles