You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript和正则表达式移除字符串中的iframe标签

移除HTML字符串中的iframe标签(按来源或全部移除)

临时方案:移除所有iframe标签

如果不需要区分来源,直接移除所有iframe,可以用正则表达式匹配完整的iframe标签(包括标签内的属性和内部内容),兼容标签大小写、属性顺序、换行等情况:

const htmlStr = '<div>正文内容<iframe src="https://example.com" width="500">嵌入内容</iframe>后续内容<iframe src="https://test.org"></iframe></div>';
// 全局移除所有iframe标签(不区分大小写)
const cleanedHtml = htmlStr.replace(/<iframe\b[^>]*>([\s\S]*?)<\/iframe>/gi, '');
console.log(cleanedHtml);

正则说明:

  • <iframe\b:匹配iframe标签开头,\b确保是完整的标签名
  • [^>]*:匹配标签内的所有属性(直到>`结束)
  • ([\s\S]*?):非贪婪匹配iframe内部的所有内容(包括换行)
  • <\/iframe>:匹配闭合标签
  • gi:全局匹配+不区分大小写模式

精准方案:按来源地址移除指定iframe

如果需要只移除特定来源的iframe,推荐两种可靠实现方式:

方法1:正则+回调函数

通过回调函数提取并判断src属性,灵活控制是否移除:

const htmlStr = '<div>正文内容<iframe src="https://example.com" width="500">嵌入内容</iframe>后续内容<iframe src="https://test.org"></iframe></div>';

const cleanedHtml = htmlStr.replace(/<iframe\b[^>]*>([\s\S]*?)<\/iframe>/gi, (fullMatch) => {
  // 提取src属性值(兼容单引号、双引号、无引号的情况)
  const srcMatch = fullMatch.match(/src=["']?([^"'>]+)["']?/i);
  if (srcMatch && srcMatch[1].includes('example.com')) {
    return ''; // 移除匹配来源的iframe
  }
  return fullMatch; // 保留其他iframe
});

console.log(cleanedHtml);

方法2:DOMParser解析(推荐复杂场景)

正则处理HTML容易出现边界情况(比如属性内包含特殊字符、标签格式不规范),用浏览器原生的DOMParser解析更稳定:

const htmlStr = '<div>正文内容<iframe src="https://example.com" width="500">嵌入内容</iframe>后续内容<iframe src="https://test.org"></iframe></div>';

// 解析HTML字符串为DOM文档
const parser = new DOMParser();
const doc = parser.parseFromString(htmlStr, 'text/html');

// 方案A:移除所有iframe
// doc.querySelectorAll('iframe').forEach(iframe => iframe.remove());

// 方案B:移除src包含指定域名的iframe
doc.querySelectorAll('iframe[src*="example.com"]').forEach(iframe => iframe.remove());

// 提取处理后的HTML字符串
const cleanedHtml = doc.body.innerHTML;
console.log(cleanedHtml);

内容的提问来源于stack exchange,提问作者Paulo Amaral

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:30:30