Search code examples
javascriptregexcomments

Commenting Regular Expressions


I'm trying to comment regular expressions in JavaScript.

There seems to be many resources on how to remove comments from code using regex, but not actually how to comment regular expressions in JavaScript so they are easier to understand.


Solution

  • Unfortunately, JavaScript doesn't have a verbose mode for regular expression literals like some other langauges do. You may find this interesting, though.

    In lieu of any external libraries, your best bet is just to use a normal string and comment that:

    var r = new RegExp(
        '('      + //start capture
        '[0-9]+' + // match digit
        ')'        //end capture
    ); 
    r.test('9'); //true