0

I have a string representing HTML, and I am trying to use str.replace(regex, "") to replace all instances of regex in a string with an empty string. The substring that I need to replace begins with <!--[if and ends with <![endif]-->, and there are multiple occurrences in the string.

Here is the regex that I tried:

const regex = /^(<!--\[if).*(<!\[endif]-->)$/g

To me, this says "a string that begins with <!--[if and ends with <![endif]--> and has any number of characters in between, while escaping the opening square brackets and using the global flag." That's what I want, so I can use str.replace:

const newString = oldString.replace(regex, "")

I'm not catching any matches. I can only think that I'm missing something about the grouping of the sequence of characters at the beginning and end.

Michael Jay
  • 156
  • 1
  • 8
  • `.` does not match everything by default. Add the `s` modifier to also let it match newlines. – trincot Aug 18 '20 at 21:04
  • Can you see anything else wrong with my regex? I added the `s` modifier and didn't get the intended result. I'm worried that I have a problem with my grouping, so the included link isn't very helpful. Although I appreciate that at least I can be certain that my regex now includes newlines. – Michael Jay Aug 18 '20 at 21:17
  • I see no issue: https://regex101.com/r/GLWxgb/2 But you also need the `m` modifier so that `^` and `$` have the meaning of beggining/end of a line, instead of beggining/end of whole text – trincot Aug 18 '20 at 21:20

0 Answers0