【问题标题】:Regex to strip line comments from html [duplicate]正则表达式从 html 中删除行注释 [重复]
【发布时间】:2017-07-26 17:13:29
【问题描述】:

我正在尝试从 html 和 css 中删除不必要的行注释。我找到了一个正则表达式来删除这样的 cmets:

/* Write your comments here */

但我正在寻找的是这样的多行评论的正则表达式:

<!-- Write your comments here 
Second line
third Line
-->

目前使用此代码删除单行 cmets:

<!--[^\[].*-->

任何帮助将不胜感激

【问题讨论】:

  • 谢谢,这正是我想要的。

标签: html css regex comments


【解决方案1】:

最好生成一个临时 DOM 元素并遍历所有节点递归删除注释节点。

var str = `
<div>
test
<!-- test comment -->
<!-- test comment -->
test

<!-- 
test comment
multiline
-->
</div>`;

// generate div element
var temp = document.createElement('div');
// set HTML content
temp.innerHTML = str;

function removeEle(e) {
  // convert child nodes into array
  Array.from(e.childNodes)
    // iterate over nodes
    .forEach(function(ele) {
      // if node type is comment then remove it
      if (ele.nodeType === 8) e.removeChild(ele);
      // if node is an element then call it recursively
      else if (ele.nodeType === 1) removeEle(ele);
    })
}

removeEle(temp);

console.log(temp.innerHTML);

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 2011-04-01
    • 2020-09-30
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 2010-11-08
    • 2012-04-08
    相关资源
    最近更新 更多