JavaScript’s regular expressions are more fun with XRegExp

[2013-02-12] dev, javascript, jslib, jslang
(Ad, please don’t block)

Reminder: As soon as your JavaScript regular expressions become more complicated, you should probably use Steven Levithan’s XRegExp library. The cool thing about XRegExp is that it internally compiles its extended regular expressions to normal regular expressions, meaning that they are fast. Let’s look at some of XRegExp’s highlights, quoted from the XRegExp website.

Highlights: insignificant whitespace, inline comments, named groups

    var date = XRegExp('(?<year>  [0-9]{4} ) -?  # year  \n' +
                       '(?<month> [0-9]{2} ) -?  # month \n' +
                       '(?<day>   [0-9]{2} )     # day     ', 'x');
The above example demonstrates three features: First, the x flag makes whitespace insignificant in regular expressions. You can spread out things as much as you like and the regular expression becomes more readable. Regular expressions can be awfully crowded; this helps. Second, with the x flag, you also get inline comments via #. Third, you can name groups (above: year, month, date). You can then use the names in match results:
    console.log(XRegExp.exec('2012-06-10', date).year);  // 2012
And in replacement strings:
                '2012-06-10', date,
                '${month}/${day}/${year}'));  // 06/10/2012

Highlight: subpatterns is a plugin for assembling a regular expression from subpatterns. For example:
    var time ='(?x)^ {{hours}} ({{minutes}}) $', {
        hours:'{{h12}} : | {{h24}}', {
            h12: /1[0-2]|0?[1-9]/,
            h24: /2[0-3]|[01][0-9]/
        }, 'x'),
        minutes: /^[0-5][0-9]$/

    console.log(time.test('10:59'));  // true
    console.log(XRegExp.exec('10:59', time).minutes);  // 59

ECMAScript 6 and XRegExp

ECMAScript 6 will have template strings which will make XRegExp even more pleasant to use.