最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript regex match iframe src - Stack Overflow

programmeradmin4浏览0评论

If I have two iframes, how can I match the one that HAS NOT a youtube src ?

<iframe  src=""></iframe>
<iframe  src=""></iframe>

If I have two iframes, how can I match the one that HAS NOT a youtube src ?

<iframe  src="http://googleads.g.doubleclick/pagead/ads?client=ca-feed-pub"></iframe>
<iframe  src="http://www.youtube./embed/Y4MnpzG5Sqc?wmode=opaque"></iframe>
Share Improve this question asked Apr 16, 2012 at 16:58 Florian ShenaFlorian Shena 1,4344 gold badges20 silver badges28 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

You have all your data in a single string, that may contain several tags? In that case you'll need to 1) find each separate iframe in string, 2) check each found iframe if you need to remove it or leave it alone. Here's the code that does just that with ments showing where each step is performed:

var string='<iframe  src="http://googleads.g.doubleclick/pagead/ads?client=ca-feed-pub"></iframe><iframe  src="http://www.youtube./embed/Y4MnpzG5Sqc?wmode=opaque"></iframe><iframe  src="http://googleads.g.doubleclick/pagead/ads?client=ca-feed-pub"></iframe><some_good_tag>TEST</some_good_tag><iframe  src="http://www.youtube./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)
var a='<iframe  src="http://googleads.g.doubleclick/pagead/ads?client=ca-feed-pub"></iframe><iframe  src="http://www.youtube./embed/Y4MnpzG5Sqc?wmode=opaque"></iframe><iframe  src="http://googleads.g.doubleclick/pagead/ads?client=ca-feed-pub"></iframe><iframe  src="http://www.youtube./"></iframe>'

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

http://jsfiddle/7ykXv/

发布评论

评论列表(0)

  1. 暂无评论