RegExp and Template Strings

JavaScript's RegExp constructor takes a string and returns a regular expression object. It is really difficult to use. Regular expressions are difficult to write because the notation is so terse and all mushed together. Writing regular expressions with string literals is even harder because of the need to double the backslashes and escape the quotes. It was recommend that you always use regular expression literals instead.

ES6 introduces a new string literal, the unfortunately named template string. It wraps a string in ` characters, allows it to span several lines, and avoids escapement. This turns out to be really helpful when composing regular expressions.

For example, make a little helper function that wraps RegExp while automatically deleting whitespace.

    function regexp(string, flags) {
        return new RegExp(string.replace(/\s/, ''), flags);
    }

Soon, instead of writing

    var rx_number = /^(0(?:b[01]+|o[0-7]+|x[0-9a-fA-F]+|\.[0-9]+(?:e[+\]?[0-9]+)?)?|[1-9][0-9]*(?:\.[0-9]+)?(?:e[+\]?[0-9]+)?)$/;

ES6 allows you to instead write

    const rx_number = regexp(`^(
        0   (?:
                b [01]+
            |   o [0-7]+
            |   x [0-9 a-f A-F]+
            |   \. [0-9]+ (?: e [+\-]? [0-9]+ )?
            )?
    |   [1-9] [0-9]*
            (?: \. [0-9]+ )? (?: e [+\-]? [0-9]+ )?

    )$`);
    
Which one would you want to maintain?

Regular expressions are still cryptic and bizarre, and I hope that someday we get a notation that is more reasonable, like the Rebol parse dialect. But until then, template strings are a huge improvement.
Shared publiclyView activity