Allowing verbose RegExp in JavaScript
Python developers enjoy the convenience of verbose - Multiline, commented Regular Expressions. Let's see if we could achieve that in JS.
by Ronny
HTML
<h1>Inspiration</h1>
<ul>
<li><a href="http://leaverou.me/2011/03/create-complex-regexps-more-easily/">Lea Verou</a></li>
<li><a href="http://diveintopython.org/regular_expressions/verbose.html">Dive Into Python</a></li>
<li><a href="http://nedbatchelder.com/blog/200304/verbose_python_regular_expressions.html">Verbose Python RegExp</a></li>
</ul>
JavaScript
var complexPattern = "^" + // Start of line
"Hello" + // hello
".*" +
/* anything else.
Multiline comments
would work as expected */
"(!|\\.)$"; // End with an exclamation mark or dot. Notice the string escaping: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp#Description
var pattern = new RegExp(complexPattern, 'gi');
var pattern2 = new RegExp("^Hello.*(!|\.)$", 'gi');
var pattern3 = /^Hello.*(!|\.)$/gi;
var string = "Hello World.";
console.log( pattern, pattern.test(string), pattern2.test(string), pattern3.test(string) );