如果我有两个 iframe,如何匹配没有 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>
如果我有两个 iframe,如何匹配没有 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>
您将所有数据都放在一个字符串中,可能包含多个标签?在这种情况下,您需要 1)在字符串中找到每个单独的 iframe,2)检查每个找到的 iframe,如果您需要删除它或不理会它。这是执行此操作的代码,其中注释显示了每个步骤的执行位置:
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)
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],'')}
}