1

Let's say I have two custom javascript comments.

Opening: //<!- and closing: //!>.

I want to replace everything in between these markers, and also the markers.

//<!- directiveDecoratorComment
    (function directiveDecorator() {
        if (typeof(angular) == 'undefined') return;
        var appElement = document.querySelector('[ng-app]');
        var appName = appElement.getAttribute('ng-app');
        if (typeof(appName) == 'undefined') return;
        var app = angular.module(appName);
        angular.forEach(app._invokeQueue, function(value, key) {
            if (value[1] == 'directive') {
                var directiveName = value[2][0];
                app.config(function($provide) {
                  $provide.decorator(directiveName + 'Directive', function($delegate) {
                    var directive = $delegate[0];
                    console.log("Decorating:",directiveName,'on',appName,'template now ==',"/views/" + directive.templateUrl);
                    directive.templateUrl = "/views/" + directive.templateUrl;
                    return $delegate;
                  });
                });
            }
        });
    }());

    //!>

So this would essentially become and empty string javascript file.

Here's what I've tried.

string.replace(/([//<])(.+\n*?)([//!>])/g, '');
Pointy
  • 405,095
  • 59
  • 585
  • 614
Shannon Hochkins
  • 11,763
  • 15
  • 62
  • 95
  • Something like [this](https://regex101.com/r/rQ1yI3/1) ? –  Feb 01 '16 at 23:12
  • Using [this answer](http://stackoverflow.com/a/10689837/3928341), this seems to work: `str.replace(/\/\/<\!-.*\/\/\!>/g, '');` – nem035 Feb 01 '16 at 23:13
  • Please read up on the meaning of a character class (`[]`) in JavaScript regexps. You could start here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-sets. –  Feb 02 '16 at 02:56

3 Answers3

1

You can use

/(\/\/<!-)([^\/]*(?:\/(?!\/!>)[^\/]*)*)(\/\/!>)/g

See regex demo

The regex is based on the unroll-the-loop technique.

  • (\/\/<!-) - match and capture literal //<!-
  • ([^\/]*(?:\/(?!\/!>)[^\/]*)*) - match and capture anything but //!> (unrolling the loop here means we match any characters but / with [^\/]* and then match zero or more groups of / that is not followed with /!> and then again any number of any characters but /)
  • (\/\/!>) - match and capture //!>

Note that you may get rid of capture groups if you are not making use of them.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

What you want is this:

string.replace(/(\/\/\<\!\-)((.*\n)*.*)(\/\/\!\>)/, '')
Jonas Meinerz
  • 612
  • 3
  • 9
0

You can do this without a look-ahead, using non-greedy matching:

/\/\/<!-[\s\S]*?\/\/!>/
 ^^^^^^^                    MATCH OPENING //<!-
        ^^^^^^^             ANYTHING IN BETWEEN
               ^^^^^^^      CLOSING //!>

The \s\S is to match newlines.