Search code examples
javascriptregexcommentsemulationinline-code

How do I include an inline comment in a regular expression in JavaScript


Inline comments works when a string passed to the RegExp constructor:

RegExp("foo"/*bar*/).test("foo")

but not with an expression. Is there any equivalent or alternative in JavaScript to emulate x-mode for the RegExp object?


Solution

  • Javascript supports neither the x modifier, nor inline comments (?#comment). See here.

    I guess, the best you can do, is to use the RegExp constructor and write every line in e separate string and concatenate them (with comments between the strings):

    RegExp(
        "foo" + // match a foo
        "bar" + // followed by a bar
        "$"     // at the end of the string
    ).test("somefoobar");