Reputation: 1165
I have the following string:
<h2><!--DEL-->This is the title<!-- /DEL --><!-- ADD--><% title %><!--/ADD--></h2>
<!--ADD-->
<strong>some emphasised text</strong>
<!--/ADD-->
<ul>
<!--ADD--><% for each item in list %> <!--/ADD--> <li><!--DEL-->This is the first item in the list<!--/DEL--><!--ADD--><% item %><!--/ADD--></li><!--ADD--><% end for %><!-- /ADD -->
<!--DEL--><li>This is the second item in the list</li><!--/DEL -->
<!--DEL--><li>This is the <strong>third</strong> item in the list</li><!-- /DEL -->
</ul>
Via regular expressions I want it to produce the following:
<h2><% title %></h2>
<strong>some emphasised text</strong>
<ul>
<% for each item in list %><li><% item %></li><% end for %>
</ul>
The regular expressions I'm using:
template = template.replace(/<\!--\s*?DEL\s*?-->(.*)<\!--\s*?\/DEL\s*?-->/gm, "");
template = template.replace(/<\!--\s*?ADD\s*?-->(.*)<\!--\s*?\/ADD\s*?-->/gm, "$1");
But at the moment it's producing:
<h2><% title %></h2>
<ul>
<% for each item in list %><!-- /ADD --><li><!-- ADD --><% item %><!-- /ADD --></li><!-- ADD --><% end for %>
</ul>
Problem 1: It doesn't seem to like it when there's multiple matches on the same line (it seems to treat them as one big match).
Problem 2: How do I make it match across multilines? I know the . character doesn't allow for new line characters, but I'm using the /m modifier (which doesn't seem to work).
Any ideas would be appreciated!
Thanks.
Upvotes: 0
Views: 53
Reputation: 1346
For problem 2. There is no DOT_ALL modificator in js. But use can use construction [\s\S] instead of dot that actually match all symbols. So finally you regexp will be
/<\!--\s*?DEL\s*?-->([\s\S]*?)<\!--\s*?\/DEL\s*?-->/gm
Upvotes: 1
Reputation: 387
Problem 1
You just need to make your wildcard lazy too:
template = template.replace(/<\!--\s*?DEL\s*?-->(.*?)<\!--\s*?\/DEL\s*?-->/gm, "");
template = template.replace(/<\!--\s*?ADD\s*?-->(.*?)<\!--\s*?\/ADD\s*?-->/gm, "$1");
Upvotes: 1