最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - How to remove html comments from a string in Javascript - Stack Overflow

programmeradmin5浏览0评论

So, I have a javascript string which is actually some html markup assigned to it.

Now, I want to remove all the html comments and its content from the string, ie all the occurrences of the opening comment tag and closing comment tag; along with the comment inside in it.

So I want to remove all occurences of

<!-- some comment -->

Please note I want ' some comment ' removed as well...

Can someone help me with the regex to replace this...

Thanks

So, I have a javascript string which is actually some html markup assigned to it.

Now, I want to remove all the html comments and its content from the string, ie all the occurrences of the opening comment tag and closing comment tag; along with the comment inside in it.

So I want to remove all occurences of

<!-- some comment -->

Please note I want ' some comment ' removed as well...

Can someone help me with the regex to replace this...

Thanks

Share Improve this question asked Jul 26, 2017 at 11:15 siddubesiddube 1351 gold badge2 silver badges10 bronze badges 5
  • Maybe convert it to a DOM node? Then loop through the ndoe elements, and remove all nodes whose type matches a comment? – evolutionxbox Commented Jul 26, 2017 at 11:16
  • Using Regular Exprssions, what if <!-- some comment --> is within a variable content var text = '<!-- some comment -->';? – revo Commented Jul 26, 2017 at 11:17
  • 2 text = text.replace(/<\!--.+?-->/sg,"") !Don't forget to add s and g modifiers – mkHun Commented Jul 26, 2017 at 11:18
  • maybe this helps: link – Amir Schnell Commented Jul 26, 2017 at 11:19
  • I think this was allready answered here – Mathias Kiekens Commented Jul 26, 2017 at 11:20
Add a comment  | 

3 Answers 3

Reset to default 15

like this

var str = `<div></div>
<!-- some comment -->
<p></p>
<!-- some comment -->`
str = str.replace(/<\!--.*?-->/g, "");
console.log(str)

i think you are looking for like this.

      var content = jQuery('body').html();
    alert(content.match(/<!--.*?-->/g));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
  <!-- some comment -->
</body>
</html>

You can use this RegEx to replace the text between <!-- and -->

/(\<!--.*?\-->)/g

Check the snippet below

var string = '<!-- some comment --><div><span>Some Content</span></div><!-- some other comment -->';

var reg = /(\<!--.*?\-->)/g;
string = string.replace(reg,"");

console.log(string);

发布评论

评论列表(0)

  1. 暂无评论