regexpu-core
regexpu is a source code transpiler that enables the use of ES6 Unicode regular expressions in JavaScript-of-today (ES5).
regexpu-core contains regexpu’s core functionality, i.e. rewritePattern(pattern, flag)
, which enables rewriting regular expressions that make use of the ES6 u
flag into equivalent ES5-compatible regular expression patterns.
Installation
To use regexpu-core programmatically, install it as a dependency via npm:
npm install regexpu-core --save
Then, require
it:
const rewritePattern = require('regexpu-core');
API
This module exports a single function named rewritePattern
.
rewritePattern(pattern, flags, options)
This function takes a string that represents a regular expression pattern as well as a string representing its flags, and returns an ES5-compatible version of the pattern.
rewritePattern('foo.bar', 'u');
rewritePattern('[\\u{1D306}-\\u{1D308}a-z]', 'u');
rewritePattern('[\\u{1D306}-\\u{1D308}a-z]', 'ui');
regexpu-core can rewrite non-ES6 regular expressions too, which is useful to demonstrate how their behavior changes once the u
and i
flags are added:
rewritePattern('foo.bar');
rewritePattern('foo.bar', 'u');
The optional options
argument recognizes the following properties:
dotAllFlag
(default: false
)
Setting this option to true
enables support for the s
(dotAll
) flag.
rewritePattern('.');
rewritePattern('.', '', {
'dotAllFlag': true
});
rewritePattern('.', 's', {
'dotAllFlag': true
});
rewritePattern('.', 'su', {
'dotAllFlag': true
});
unicodePropertyEscape
(default: false
)
Setting this option to true
enables support for Unicode property escapes:
rewritePattern('\\p{Script_Extensions=Anatolian_Hieroglyphs}', 'u', {
'unicodePropertyEscape': true
});
lookbehind
(default: false
)
Setting this option to true
enables support for lookbehind assertions.
rewritePattern('(?<=.)a', '', {
'lookbehind': true
});
namedGroup
(default: false
)
Setting this option to true
enables support for named capture groups.
rewritePattern('(?<name>.)\k<name>', '', {
'namedGroups': true
});
onNamedGroup
This option is a function that gets called when a named capture group is found. It receives two parameters:
the name of the group, and its index.
rewritePattern('(?<name>.)\k<name>', '', {
'namedGroups': true,
onNamedGroup(name, index) {
console.log(name, index);
}
});
useUnicodeFlag
(default: false
)
Setting this option to true
enables the use of Unicode code point escapes of the form \u{…}
. Note that in regular expressions, such escape sequences only work correctly when the ES6 u
flag is set. Enabling this setting often results in more compact output, although there are cases (such as \p{Lu}
) where it actually increases the output size.
rewritePattern('\\p{Script_Extensions=Anatolian_Hieroglyphs}', 'u', {
'unicodePropertyEscape': true,
'useUnicodeFlag': true
});
Author
License
regexpu-core is available under the MIT license.