Ignoring whitespace in Javascript regular expression patterns?

后端 未结 2 1114
無奈伤痛
無奈伤痛 2021-01-17 09:52

From my research it looks like Javascript\'s regular expressions don\'t have any built-in equivalent to Perl\'s /x modifier, or .NET\'s RegexOptions.IgnorePatternWhitespace

2条回答
  •  深忆病人
    2021-01-17 10:36

    Unfortunately there isn't such option in ES5, and I suspect it's unlikely to ever be in RegExp literals, because they're already very hard to parse and line breaks would make them even more ambiguous.

    If you want easy escaping and syntax highlighting of RegExp literals, you can join them by taking advantage of the source property. It's not perfect, but IMHO less bad than falling all the way back to strings:

    new RegExp(
        /foo/.source +
        /[\d+]/.source +
        /bar/.source
    );
    

    In ES6 you can create your own template string:

    regexp`
      foo
      [\d+]
      bar
    `;
    
    function regexp(parts) {
       // I'm ignoring support for ${} placeholders for brevity,
       // but full implementation should escape them.
    
       // Note that `.raw` allows use of \d instead of \\d.
       return new RegExp(parts.raw.join('').replace(/\s+/g,''));
    }
    

提交回复
热议问题