4

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

5
  • Maybe convert it to a DOM node? Then loop through the ndoe elements, and remove all nodes whose type matches a comment? Commented Jul 26, 2017 at 11:16
  • Using Regular Exprssions, what if <!-- some comment --> is within a variable content var text = '<!-- some comment -->';? Commented Jul 26, 2017 at 11:17
  • 2
    text = text.replace(/<\!--.+?-->/sg,"") !Don't forget to add s and g modifiers Commented Jul 26, 2017 at 11:18
  • maybe this helps: link Commented Jul 26, 2017 at 11:19
  • I think this was allready answered here Commented Jul 26, 2017 at 11:20

3 Answers 3

15

like this

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

Sign up to request clarification or add additional context in comments.

1 Comment

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...
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>

Comments

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

2 Comments

What is the use of i modifier in your code? Better you can add s modifier also.
Why the extra parenthesis (capture group around the entire regex)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.