0

I have the following markdown file with a series of HTML style comments in them:

hello this is my file

<!-- START COMMENT -->
<!-- END COMMENT -->

the rest of the file

Sometimes the comment tags are empty, and other times they will have content within them:

hello this is my file

<!-- START COMMENT -->
some
content
here
<!-- END COMMENT -->

the rest of the file

I'm trying to replace the contents of the tags, but keep the tags intact so they still surround the content. I've tried the following regex, but it seems to replace the tags as well, which is not what I need:

data = data.replace(
  /<!-- START COMMENT -->[\s\S]*?<!-- END COMMENT -->/g,
  generatePlaceholders(response)
)

How can I adjust my regex so it only replaces the contents?

James Ives
  • 3,177
  • 3
  • 30
  • 63

1 Answers1

2

You could do replacements that reinserts the comments with the replacement text. If you put the <!-- START COMMENT --> and <!-- END COMMENT --> inside matching groups you can reference them again and inset them again (with $1 & $2 being the start and end) while replacing the content inside.

const p = document.getElementById('content').innerHTML;
const replacement = 'new content';

console.log(p.replace(/(<!-- START COMMENT -->)[\s\S]*?(<!-- END COMMENT -->)/, `$1${replacement}$2`));
<div id="content">
hello this is my file

<!-- START COMMENT -->
some
content
here
<!-- END COMMENT -->

the rest of the file
</div>
Nils Kähler
  • 2,645
  • 1
  • 21
  • 26