【问题标题】:JavaScript sanitize HTML string and remove ID, class and other attributesJavaScript 清理 HTML 字符串并删除 ID、类和其他属性
【发布时间】:2019-03-20 06:25:51
【问题描述】:

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

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 从所有标签 OTHER 中删除 ID、Class 或任何属性,然后是 &lt;PRE&gt;&lt;CODE&gt; 标签。

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

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);
}

如果您需要更多信息,请告诉我。

【问题讨论】:

  • 感谢@Neal,更正。我尝试了很多正确对齐代码但不明白为什么它与我的文本合并。
  • 到底是什么问题?您的代码已成功从 &lt;p&gt; 标记中删除 id 属性,您只是没有任何代码可以删除任何其他属性。
  • 嗨@Herohtar,后来我检查了它,正如你提到的那样它正在工作。谢谢。

标签: javascript html


【解决方案1】:

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

   
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));

【讨论】:

  • 嗨@Dacre Denny,感谢您的回复。由于其他任务,我无法测试此解决方案,但会尝试更新。
  • @JigneshRaval 没问题,希望对您有所帮助!
猜你喜欢
  • 2021-11-01
  • 2019-04-19
  • 2011-04-08
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 1970-01-01
相关资源
最近更新 更多