[!TIP]
XRegExp was indispensable for heavy regex users in its time, but many of its best features have been adopted into modern JavaScript. Check out Regex+, the lightweight spiritual successor to XRegExp that once again takes JavaScript regexes to the next level.
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 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 thisconst name = XRegExp.exec(str, regexWithNamedCapture).name;// To thisconst 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 commentsconst 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 propertylet match = XRegExp.exec('2021-02-22', date);match.groups.year; // -> '2021'// It also includes optional pos and sticky argumentslet pos = 3;const result = [];while (match = XRegExp.exec('<1><2><3>4<5>', /<(\d+)>/, pos, 'sticky')) { result.push(match[1]);
These examples give the flavor of what's possible, but XRegExp has more syntax, flags, methods, options, and browser fixes that aren't shown here. You can also augment XRegExp's regular expression syntax with addons (see below) or write your own. See xregexp.com for details.
If not using xregexp-all.js, first include the Unicode Base script and then one or more of the addons for Unicode categories, properties, or scripts.
Then you can do this:
// Test some Unicode scripts// Can also use the Script= prefix to match ES2018: \p{Script=Hiragana}XRegExp('^\\p{Hiragana}+$').test('ひらがな'); // -> trueXRegExp('^[\\p{Latin}\\p{Common}]+$').test('Über Café.'); // -> true// Test the Unicode categories Letter and Mark// Can also use the short names \p{L} and \p{M}const unicodeWord = XRegExp.tag()`^\p{Letter}[\p{Letter}\p{Mark}]*$`;unicodeWord.test('Русский'); // -> trueunicodeWord.test('日本語'); // -> trueunicodeWord.
By default, \p{…} and \P{…} support the Basic Multilingual Plane (i.e. code points up to U+FFFF). You can opt-in to full 21-bit Unicode support (with code points up to U+10FFFF) on a per-regex basis by using flag A. This is called astral mode. You can automatically add flag A for all new regexes by running XRegExp.install('astral'). When in astral mode, \p{…} and \P{…} always match a full code point rather than a code unit, using surrogate pairs for code points above U+FFFF.
// Using flag A to match astral code pointsXRegExp('^\\p{S}$').test('💩'); // -> falseXRegExp('^\\p{S}$', 'A').test('💩'); // -> true// Using surrogate pair U+D83D U+DCA9 to represent U+1F4A9 (pile of poo)XRegExp('^\\p{S}$', 'A').test('\uD83D\uDCA9'); // -> true// Implicit flag AXRegExp.install('astral');XRegExp('^\\p{S}$').test('💩'); // -> true
Opting in to astral mode disables the use of \p{…} and \P{…} within character classes. In astral mode, use e.g. (\pL|[0-9_])+ instead of [\pL0-9_]+.
XRegExp uses Unicode 14.0.0.
XRegExp.build
Build regular expressions using named subpatterns, for readability and pattern reuse:
Named subpatterns can be provided as strings or regex objects. A leading ^ and trailing unescaped $ are stripped from subpatterns if both are present, which allows embedding independently-useful anchored patterns. {{…}} tokens can be quantified as a single unit. Any backreferences in the outer pattern or provided subpatterns are automatically renumbered to work correctly within the larger combined pattern. The syntax ({{name}}) works as shorthand for named capture via (?<name>{{name}}). Named subpatterns cannot be embedded within character classes.
XRegExp.tag (included with XRegExp.build)
Provides tagged template literals that create regexes with XRegExp syntax and flags:
XRegExp.tag does more than just interpolation. You get all the XRegExp syntax and flags, and since it reads patterns as raw strings, you no longer need to escape all your backslashes. XRegExp.tag also uses XRegExp.build under the hood, so you get all of its extras for free. Leading ^ and trailing unescaped $ are stripped from interpolated patterns if both are present (to allow embedding independently useful anchored regexes), interpolating into a character class is an error (to avoid unintended meaning in edge cases), interpolated patterns are treated as atomic units when quantified, interpolated strings have their special characters escaped, and any backreferences within an interpolated regex are rewritten to work within the overall pattern.
XRegExp.matchRecursive
A robust and flexible API for matching recursive constructs using XRegExp pattern strings as left and right delimiters:
By default, XRegExp.matchRecursive throws an error if it scans past an unbalanced delimiter in the target string. Multiple alternative options are available for handling unbalanced delimiters.
Installation and usage
In browsers (bundle XRegExp with all of its addons):
Install the pnpm version pinned in package.json, then run:
pnpm installpnpm test
pnpm test builds the Unicode data, lints and compiles the source, bundles XRegExp,
and runs the test suite. Use pnpm run build to build without running the tests.