Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex to match everything between 2 html comment tags

I have to create a regex which will match anything (including line breaks) between 2 html specific comment tags. Here is an example for some html:

<!-- build-remove-start -->
<!-- bower:js -->
<script src="../bower_components/jquery/dist/jquery.js"></script>
<!-- endbower -->
<!-- build-remove-end -->

<!-- inject:vendor:js -->
<!-- endinject -->

I would like to match every thing between <!-- build-remove-start --> and <!-- build-remove-end --> not including the comment tags (I mean not to remove the comments tags, only what's inside).
I have tried:
<!-- build-remove-start -->[\s\S]<!-- build-remove-end -->
But it doesn't work. Here is a link to test the regex:
https://regex101.com/r/rV0qG2/2

like image 352
vlio20 Avatar asked Apr 10 '26 20:04

vlio20


1 Answers

You need to add * after [\s\S].

/<!-- build-remove-start -->([\s\S]*?)<!-- build-remove-end -->/gmi

Also I recommend adding ? after * so it makes it lazy. This way you can have the example below, othwerise the this won't be removed line will be matched.

<!-- build-remove-start -->
//remove this
<!-- build-remove-end -->

This won't be removed

<!-- build-remove-start -->
//Remove this
<!-- build-remove-end -->
like image 118
Marcos Casagrande Avatar answered Apr 12 '26 09:04

Marcos Casagrande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!