README
XRegExp 5.1.0
XRegExp provides augmented (and extensible) JavaScript regular expressions. You get modern syntax and flags beyond what browsers support natively. XRegExp is also a regex utility belt with tools to make your grepping and parsing easier, while freeing you from regex cross-browser inconsistencies and other annoyances.
XRegExp supports all native ES6 regular expression syntax. It supports ES5+ browsers, and you can use it with Node.js or as a RequireJS module. Over the years, many of XRegExp's features have been adopted by new JavaScript standards (named capturing, Unicode properties/scripts/categories, flag s
, sticky matching, etc.), so using XRegExp can be a way to extend these features into older browsers.
Performance
XRegExp compiles to native RegExp
objects. Therefore regexes built with XRegExp perform just as fast as native regular expressions. There is a tiny extra cost when compiling a pattern for the first time.
Named capture breaking change in XRegExp 5
XRegExp 5 introduced a breaking change where named backreference properties now appear on the result's groups
object (following ES2018), rather than directly on the result. To restore the old handling so you don't need to update old code, run the following line after importing XRegExp:
XRegExp.uninstall('namespacing');
XRegExp 4.1.0 and later allow introducing the new behavior without upgrading to XRegExp 5 by running XRegExp.install('namespacing')
.
Following is the most commonly needed change to update code for the new behavior:
// Change this
const name = XRegExp.exec(str, regexWithNamedCapture).name;
// To this
const name = XRegExp.exec(str, regexWithNamedCapture).groups.name;
See below for more examples of using named capture with XRegExp.exec
and XRegExp.replace
.
Usage examples
// Using named capture and flag x for free-spacing and line comments
const date = XRegExp(
`(?<year> [0-9]{4} ) -? # year
(?<month> [0-9]{2} ) -? # month
(?<day> [0-9]{2} ) # day`, 'x');
// XRegExp.exec provides named backreferences on the result's groups property
let match = XRegExp.exec('2021-02-22', date);
match.groups.year; // -> '2021'
// It also includes optional pos and sticky arguments
let pos = 3;
const result = [];
while (match = XRegExp.exec('<1><2><3>4<5>', /<(\d+)>/, pos, 'sticky')) {
result.push(match[1]);
pos = match.index + match[0].length;
}
// result -> ['2', '3']
// XRegExp.replace allows named backreferences in replacements
XRegExp.replace('2021-02-22', date, '