1

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

siddube
  • 75
  • 1
  • 8

3 Answers3

8

like this

var str = `<div></div>
<!-- some comment -->
<p></p>
<!-- some comment -->`
str = str.replace(/<\!--.*?-->/g, "");
console.log(str)
ewwink
  • 15,852
  • 2
  • 35
  • 50
  • Thanks... this regex is working... I also tried using split and join on particular comments and it was working but I preferred to do it with regex and on all comments... Thanks, and also accepted because it's vanilla javascript... – siddube Jul 26 '17 at 11:33
1

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);
Munawir
  • 3,196
  • 8
  • 31
  • 47
1

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>