如果我有两个 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)
关于Javascript 正则表达式匹配 iframe src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10178387/