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 modifier. These are very useful as they can make a complex regex much easier to read. Firstly, have I missed something and is there a Javascript built-in equivalent to these? Secondly, if there isn't, does anyone know of a good jQuery plugin that will implement this functionality? It's a shame to have to compress my complex regex into one line because of Javascript's apparent regex limitations.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
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 thesource
property. It's not perfect, but IMHO less bad than falling all the way back to strings:In ES6 you can create your own template string:
If I understand you correctly you want to add white space that isn't part of the regexp? As far as I know it isn't possible with literal regexp.
Example:
You can break up the regexp in several lines like this:
Notice that since it is now a normal string, you have to escape \ with \\
Or if you have a complex one:
Update: Using a temporary array to concatenate the regular expression: