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

如何用JQuery/JS检测并移除文本框中未允许的HTML标签?

HTML标签白名单检测、清理及同类工具方案

一、检测textarea中的未允许HTML标签

通过正则匹配textarea内的所有HTML标签,与预设白名单对比后,即可找出违规标签并反馈给用户。以下是纯JavaScript实现示例:

// 预设允许的标签白名单
const allowedTags = ['a', 'p', 'div'];
// 获取目标元素
const textarea = document.getElementById('content-textarea');
const checkBtn = document.getElementById('check-btn');

checkBtn.addEventListener('click', () => {
  const content = textarea.value;
  // 匹配所有HTML标签(含闭合标签)
  const tagRegex = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
  const foundTags = new Set();
  let matchResult;

  // 提取所有出现过的标签名
  while ((matchResult = tagRegex.exec(content)) !== null) {
    const tagName = matchResult[1].toLowerCase();
    foundTags.add(tagName);
  }

  // 筛选出不在白名单内的违规标签
  const forbiddenTags = [...foundTags].filter(tag => !allowedTags.includes(tag));
  
  // 向用户反馈结果
  if (forbiddenTags.length > 0) {
    alert(`检测到违规标签:${forbiddenTags.join(', ')}`);
  } else {
    alert('所有标签均符合要求');
  }
});

二、移除未允许标签并保留内容

通过创建临时DOM节点解析HTML内容,遍历节点后仅保留白名单内的标签结构,最终将清理后的内容放回textarea:

const cleanBtn = document.getElementById('clean-btn');

cleanBtn.addEventListener('click', () => {
  const content = textarea.value;
  // 创建临时容器用于解析HTML
  const tempContainer = document.createElement('div');
  tempContainer.innerHTML = content;

  // 递归清理节点
  function cleanNode(node) {
    if (node.nodeType === Node.ELEMENT_NODE) {
      const tagName = node.tagName.toLowerCase();
      if (!allowedTags.includes(tagName)) {
        // 违规标签直接替换为其子节点,保留内容
        while (node.firstChild) {
          node.parentNode.insertBefore(node.firstChild, node);
        }
        node.parentNode.removeChild(node);
        return;
      }
    }
    // 递归处理子节点
    let child = node.firstChild;
    while (child) {
      const nextChild = child.nextSibling;
      cleanNode(child);
      child = nextChild;
    }
  }

  cleanNode(tempContainer);
  // 将清理后的内容写回textarea
  textarea.value = tempContainer.innerHTML;
  alert('违规标签已移除');
});

三、现成客户端标签过滤工具

有成熟的客户端工具可实现类似Stack Overflow的预览标签过滤功能,DOMPurify是最优选择:

  • 专注于XSS防护与HTML内容净化,支持自定义标签/属性白名单
  • 自动移除<style>、<script>等恶意标签及危险属性,同时保留合法内容结构
  • 无需后端依赖,纯客户端运行,配置简单

示例用法:

// 配置白名单并净化内容
const purifiedContent = DOMPurify.sanitize(textarea.value, {
  ALLOWED_TAGS: allowedTags,
  ALLOWED_ATTR: ['href', 'target'] // 可额外指定允许的标签属性
});
// 将净化后的内容赋值给textarea或预览区域
textarea.value = purifiedContent;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:30:41