首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaScript清理HTML字符串并删除ID、类和其他属性

JavaScript清理HTML字符串并删除ID、类和其他属性
EN

Stack Overflow用户
提问于 2018-10-16 03:08:55
回答 1查看 1.4K关注 0票数 3

我需要帮助来消毒我的HTML文本由用户提供。我有以下HTML代码:

代码语言:javascript
复制
var htmlStr = `<p id="test" class="mydemo">TEhis is test</p>
   <pre class="css">
      &lt;html>
          &lt;body class="test">&lt;/body>
      &lt;/html>
   </pre>`;

我想使用普通的JavaScript从除<PRE><CODE>标记之外的所有标记中删除ID、类或任何属性。

我尝试了以下操作,但没有得到正确的输出:

代码语言:javascript
复制
sanitizeHtml(html: any) {
    let temp = document.createElement('div');
    temp.innerHTML = html;
    // let t1 = temp.querySelectorAll('*');

    temp.querySelectorAll('*').forEach(node => {
        if(node.nodeName !== 'PRE') {
            return node.removeAttribute('id');
        }
    })

    console.log(temp);

    // return html.replace(/\s*(\w+)=\"[^\"]+\"/gim, '').replace(/<script>[\w\W\s\S]+<\/script>/gim);
}

如果您需要进一步的信息,请让我知道。

EN

回答 1

Stack Overflow用户

发布于 2018-10-16 03:25:46

这有点机械,也许不是最好的解决方案,但是你可以通过以下正则表达式链接.replace()来根据需要清理你的HTML字符串:

代码语言:javascript
复制
function sanitizeHtml(html) {

  var htmlSanitized = html
  .replace(/<pre[\w\s"=]*>/gi, function(match) { 
      // Add a place holder to attrbitues on pre elements to prevent
      // removal of these in subsequent step
      return match.replace(/=/gi, 'EQUALS')
  })
  .replace(/\w+="\w+"/gi,'')
  .replace(/\s+>/gi,'>')
  .replace(/EQUALS/i,'=')

  return htmlSanitized;
}

var htmlStr = `<p id="test" class="mydemo">TEhis is test</p>
   <pre class="css">
      &lt;html>
          &lt;body class="test">&lt;/body>
      &lt;/html>
   </pre>`;

console.log(sanitizeHtml(htmlStr));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52823283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档