-1

I need a regex in javascript, that replaces all occurences of <!-- foo --> in a string.

I tried:

thestring.replace(/<!--[\s\S]*-->/gm, "")

but that doesn't work, and even breaks my text.

I can't use .* as that excludes newlines.

Sample multiline comment:

<!-- foo
    bar
          baz-->
lonix
  • 14,255
  • 23
  • 85
  • 176

2 Answers2

2

try:

thestring.replace(/<!--[^]*-->/gm, "")

or use lazy ? to make the previous quantifier find the shortest match:

thestring.replace(/<!--[^]*?-->/gm, "")
                           ^
<!-- a comment here -->  oops, ignore? -->
^^^^^^^^^^^^^^^^^^^^^^^

As a side note, if you're trying to parse html using regexp, I suggest you take a look at the top answer here: RegEx match open tags except XHTML self-contained tags

pratiqdev
  • 51
  • 1
  • 6
dustytrash
  • 1,568
  • 1
  • 10
  • 17
0

Try this one: /<!--[\w\s]+-->/g

const re = /<!--[\w\s]+-->/g
const str = 'test <!-- foo --> abc'
console.log(str.replace(re, ''))

Edit: OP's code seems fine?

CodeDraken
  • 1,163
  • 6
  • 12