Instantly share code, notes, and snippets.

Embed
What would you like to do?
Thoughts on use of template strings with XRegExp and ES6
When browsers implement ES6 template strings, add tags XRegExp.r (regex as raw string) and
XRegExp.rx (regex with implicit free-spacing, as raw string). Don't need tag XRegExp.raw (raw
string), because you should be able to use, e.g., XRegExp(String.raw`\w`). Don't need to support
flags /gy (which XRegExp doesn't allow in mode modifiers) with XRegExp.r/rx, since XRegExp methods
provide alternate mechanisms for /gy (scope 'all', the sticky option, lack of need for lastIndex
updating, and the XRegExp.globalize method if you really need it). All other flags (e.g., /im and
custom flags /snxA) can be applied via a leading mode modifier (e.g., XRegExp.r`(?s).`).
If the above sounds confusing, keep in mind that you can simply maintain the status quo but still
gain the benefits of raw multiline template strings (no more double escaping!) via, e.g.,
XRegExp(r`pattern`, flags), assuming String.raw is aliased as r. However, the new tags will allow
usage like this:
~~~
XRegExp.install('natives');
var regex = XRegExp.rx;
var str = '/2012/10/Page.html';
var parts = str.match(regex`
^ # match at start of string only
/ (?<year> [^/]+ ) # capture top dir name as year
/ (?<month> [^/]+ ) # capture subdir name as month
/ (?<title> [^/]+ ) # capture file name without ext as title
\.html? $ # .htm or .html file ext at end of path
`);
+parts.year; // -> 2012
~~~
Compare that regex to the following:
~~~
var parts = str.match(XRegExp(
'^ # match at start of string only \n' +
'/ (?<year> [^/]+ ) # capture top dir name as year \n' +
'/ (?<month> [^/]+ ) # capture subdir name as month \n' +
'/ (?<title> [^/]+ ) # capture file name without ext as title \n' +
'\\.html? $ # .htm or .html file ext at end of path ', 'x'
));
~~~
...And this is a rare regex string that needs only one double escaping!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment