Socket
Socket
Sign inDemoInstall

xregexp

Package Overview
Dependencies
Maintainers
2
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

xregexp - npm Package Compare versions

Comparing version 4.4.1 to 5.0.0

lib/addons/index.js

8

package.json
{
"name": "xregexp",
"version": "4.4.1",
"version": "5.0.0",
"description": "Extended regular expressions",

@@ -32,7 +32,7 @@ "homepage": "http://xregexp.com/",

"babel": "babel src -d lib",
"build-unicode-data": "node tools/scripts/block-regex.js && node tools/scripts/category-regex.js && node tools/scripts/property-regex.js && node tools/scripts/script-regex.js",
"build-unicode-data": "node tools/scripts/category-regex.js && node tools/scripts/property-regex.js && node tools/scripts/script-regex.js",
"prebuild": "npm run build-unicode-data && npm run lint && npm run babel",
"build": "browserify lib/index.js --standalone XRegExp > xregexp-all.js",
"pretest": "npm run build",
"test": "jasmine JASMINE_CONFIG_PATH=tests/jasmine.json",
"test": "nyc --reporter=lcov --reporter=text-summary jasmine JASMINE_CONFIG_PATH=tests/jasmine.json",
"test-saucelabs": "npm run pretest && zuul tests/spec/*.js",

@@ -46,2 +46,3 @@ "test-browser": "npm run test-saucelabs -- --local --open",

"@babel/core": "^7.12.3",
"@babel/plugin-proposal-unicode-property-regex": "^7.12.1",
"@babel/plugin-transform-runtime": "^7.12.1",

@@ -58,2 +59,3 @@ "@babel/preset-env": "^7.12.1",

"jsesc": "^3.0.1",
"nyc": "^15.1.0",
"unicode-property-value-aliases": "^3.5.0",

@@ -60,0 +62,0 @@ "zuul": "^3.12.0"

@@ -1,2 +0,2 @@

# XRegExp 4.4.1
# XRegExp 5.0.0-next

@@ -7,3 +7,3 @@ [![Build Status](https://github.com/slevithan/xregexp/workflows/Node.js%20CI/badge.svg)](https://github.com/slevithan/xregexp/actions)

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.
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.

@@ -14,2 +14,24 @@ ## Performance

## 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:
```js
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:
```js
// 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

@@ -24,5 +46,5 @@

// XRegExp.exec gives you named backreferences on the match result
let match = XRegExp.exec('2017-02-22', date);
match.year; // -> '2017'
// XRegExp.exec provides named backreferences on the result's groups property
let match = XRegExp.exec('2021-02-22', date);
match.groups.year; // -> '2021'

@@ -39,18 +61,19 @@ // It also includes optional pos and sticky arguments

// XRegExp.replace allows named backreferences in replacements
XRegExp.replace('2017-02-22', date, '$<month>/$<day>/$<year>');
// -> '02/22/2017'
XRegExp.replace('2017-02-22', date, (match) => {
return `${match.month}/${match.day}/${match.year}`;
XRegExp.replace('2021-02-22', date, '$<month>/$<day>/$<year>');
// -> '02/22/2021'
XRegExp.replace('2021-02-22', date, (...args) => {
// Named backreferences are on the last argument
const groups = args.pop();
return `${groups.month}/${groups.day}/${groups.year}`;
});
// -> '02/22/2017'
// -> '02/22/2021'
// XRegExps compile to RegExps and work perfectly with native methods
date.test('2017-02-22');
// XRegExps compile to RegExps and work with native methods
date.test('2021-02-22');
// -> true
// However, named captures must be referenced using numbered backreferences
// if used with native methods
'2021-02-22'.replace(date, '$2/$3/$1');
// -> '02/22/2021'
// The only caveat is that named captures must be referenced using
// numbered backreferences if used with native methods
'2017-02-22'.replace(date, '$2/$3/$1');
// -> '02/22/2017'
// Use XRegExp.forEach to extract every other digit from a string

@@ -65,3 +88,3 @@ const evens = [];

XRegExp.matchChain('1 <b>2</b> 3 <B>4 \n 56</B>', [
XRegExp('(?is)<b>.*?</b>'),
XRegExp('<b>.*?</b>', 'is'),
/\d+/

@@ -94,3 +117,3 @@ ]);

If not using `xregexp-all.js`, first include the Unicode Base script and then one or more of the addons for Unicode blocks, categories, properties, or scripts.
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.

@@ -100,11 +123,13 @@ Then you can do this:

```js
// Test the Unicode category L (Letter)
const unicodeWord = XRegExp('^\\pL+$');
// Test some Unicode scripts
// Can also use the Script= prefix to match ES2018: \p{Script=Hiragana}
XRegExp('^\\p{Hiragana}+$').test('ひらがな'); // -> true
XRegExp('^[\\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('Русский'); // -> true
unicodeWord.test('日本語'); // -> true
unicodeWord.test('العربية'); // -> true
// Test some Unicode scripts
XRegExp('^\\p{Hiragana}+$').test('ひらがな'); // -> true
XRegExp('^[\\p{Latin}\\p{Common}]+$').test('Über Café.'); // -> true
```

@@ -116,11 +141,10 @@

// Using flag A to match astral code points
XRegExp('^\\pS$').test('💩'); // -> false
XRegExp('^\\pS$', 'A').test('💩'); // -> true
XRegExp('(?A)^\\pS$').test('💩'); // -> true
XRegExp('^\\p{S}$').test('💩'); // -> false
XRegExp('^\\p{S}$', 'A').test('💩'); // -> true
// Using surrogate pair U+D83D U+DCA9 to represent U+1F4A9 (pile of poo)
XRegExp('(?A)^\\pS$').test('\uD83D\uDCA9'); // -> true
XRegExp('^\\p{S}$', 'A').test('\uD83D\uDCA9'); // -> true
// Implicit flag A
XRegExp.install('astral');
XRegExp('^\\pS$').test('💩'); // -> true
XRegExp('^\\p{S}$').test('💩'); // -> true
```

@@ -146,3 +170,3 @@

time.test('10:59'); // -> true
XRegExp.exec('10:59', time).minutes; // -> '59'
XRegExp.exec('10:59', time).groups.minutes; // -> '59'
```

@@ -157,13 +181,16 @@

```js
const h12 = /1[0-2]|0?[1-9]/;
const h24 = /2[0-3]|[01][0-9]/;
const hours = XRegExp.tag('x')`${h12} : | ${h24}`;
const minutes = /^[0-5][0-9]$/;
// Note that explicitly naming the 'minutes' group is required for named backreferences
const time = XRegExp.tag('x')`^ ${hours} (?<minutes>${minutes}) $`;
XRegExp.tag()`\b\w+\b`.test('word'); // -> true
const hours = /1[0-2]|0?[1-9]/;
const minutes = /(?<minutes>[0-5][0-9])/;
const time = XRegExp.tag('x')`\b ${hours} : ${minutes} \b`;
time.test('10:59'); // -> true
XRegExp.exec('10:59', time).minutes; // -> '59'
XRegExp.exec('10:59', time).groups.minutes; // -> '59'
const backref1 = /(a)\1/;
const backref2 = /(b)\1/;
XRegExp.tag()`${backref1}${backref2}`.test('aabb'); // -> true
```
XRegExp.tag does more than just basic interpolation. For starters, you get all the XRegExp syntax and flags. Even better, since `XRegExp.tag` uses your pattern as a raw string, you no longer need to escape all your backslashes. And since it relies on `XRegExp.build` under the hood, 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.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.

@@ -233,10 +260,2 @@ ### XRegExp.matchRecursive

In an AMD loader like [RequireJS](http://requirejs.org/):
```js
require({paths: {xregexp: 'xregexp-all'}}, ['xregexp'], (XRegExp) => {
console.log(XRegExp.version);
});
```
## Credits

@@ -243,0 +262,0 @@

/*!
* XRegExp.build 4.4.1
* XRegExp.build 5.0.0
* <xregexp.com>

@@ -90,10 +90,13 @@ * Steven Levithan (c) 2012-present MIT License

*
* const h12 = /1[0-2]|0?[1-9]/;
* const h24 = /2[0-3]|[01][0-9]/;
* const hours = XRegExp.tag('x')`${h12} : | ${h24}`;
* const minutes = /^[0-5][0-9]$/;
* // Note that explicitly naming the 'minutes' group is required for named backreferences
* const time = XRegExp.tag('x')`^ ${hours} (?<minutes>${minutes}) $`;
* XRegExp.tag()`\b\w+\b`.test('word'); // -> true
*
* const hours = /1[0-2]|0?[1-9]/;
* const minutes = /(?<minutes>[0-5][0-9])/;
* const time = XRegExp.tag('x')`\b ${hours} : ${minutes} \b`;
* time.test('10:59'); // -> true
* XRegExp.exec('10:59', time).minutes; // -> '59'
* XRegExp.exec('10:59', time).groups.minutes; // -> '59'
*
* const backref1 = /(a)\1/;
* const backref2 = /(b)\1/;
* XRegExp.tag()`${backref1}${backref2}`.test('aabb'); // -> true
*/

@@ -129,3 +132,3 @@ XRegExp.tag = (flags) => (literals, ...substitutions) => {

* time.test('10:59'); // -> true
* XRegExp.exec('10:59', time).minutes; // -> '59'
* XRegExp.exec('10:59', time).groups.minutes; // -> '59'
*/

@@ -132,0 +135,0 @@ XRegExp.build = (pattern, subs, flags) => {

/*!
* XRegExp.matchRecursive 4.4.1
* XRegExp.matchRecursive 5.0.0
* <xregexp.com>

@@ -32,3 +32,3 @@ * Steven Levithan (c) 2009-present MIT License

* @param {String} right Right delimiter as an XRegExp pattern.
* @param {String} [flags] Any native or XRegExp flags, used for the left and right delimiters.
* @param {String} [flags] Any combination of XRegExp flags, used for the left and right delimiters.
* @param {Object} [options] Lets you specify `valueNames` and `escapeChar` options.

@@ -115,3 +115,3 @@ * @returns {!Array} Array of matches, or an empty array.

// Flags `gy` not needed here
flags.replace(/[^imu]+/g, '')
flags.replace(XRegExp._hasNativeFlag('s') ? /[^imsu]/g : /[^imu]/g, '')
);

@@ -185,3 +185,5 @@ }

} else {
throw new Error('Unbalanced delimiter found in string');
const delimSide = rightMatch ? 'right' : 'left';
const errorPos = rightMatch ? delimStart : outerStart;
throw new Error(`Unbalanced ${delimSide} delimiter found in string at position ${errorPos}`);
}

@@ -188,0 +190,0 @@ // If the delimiter matched an empty string, avoid an infinite loop

/*!
* XRegExp Unicode Base 4.4.1
* XRegExp Unicode Base 5.0.0
* <xregexp.com>

@@ -29,2 +29,3 @@ * Steven Levithan (c) 2008-present MIT License

const unicode = {};
const unicodeTypes = {};

@@ -127,3 +128,3 @@ // Reuse utils

// Use `*` instead of `+` to avoid capturing `^` as the token name in `\p{^}`
/\\([pP])(?:{(\^?)([^}]*)}|([A-Za-z]))/,
/\\([pP])(?:{(\^?)(?:(\w+)=)?([^}]*)}|([A-Za-z]))/,
(match, scope, flags) => {

@@ -135,18 +136,33 @@ const ERR_DOUBLE_NEG = 'Invalid double negation ';

const ERR_ASTRAL_IN_CLASS = 'Astral mode does not support Unicode tokens within character classes';
const [
fullToken,
pPrefix,
caretNegation,
typePrefix,
tokenName,
tokenSingleCharName
] = match;
// Negated via \P{..} or \p{^..}
let isNegated = match[1] === 'P' || !!match[2];
let isNegated = pPrefix === 'P' || !!caretNegation;
// Switch from BMP (0-FFFF) to astral (0-10FFFF) mode via flag A
const isAstralMode = flags.includes('A');
// Token lookup name. Check `[4]` first to avoid passing `undefined` via `\p{}`
let slug = normalize(match[4] || match[3]);
// Token lookup name. Check `tokenSingleCharName` first to avoid passing `undefined`
// via `\p{}`
let slug = normalize(tokenSingleCharName || tokenName);
// Token data object
let item = unicode[slug];
if (match[1] === 'P' && match[2]) {
throw new SyntaxError(ERR_DOUBLE_NEG + match[0]);
if (pPrefix === 'P' && caretNegation) {
throw new SyntaxError(ERR_DOUBLE_NEG + fullToken);
}
if (!unicode.hasOwnProperty(slug)) {
throw new SyntaxError(ERR_UNKNOWN_NAME + match[0]);
throw new SyntaxError(ERR_UNKNOWN_NAME + fullToken);
}
if (typePrefix) {
if (!(unicodeTypes[typePrefix] && unicodeTypes[typePrefix][slug])) {
throw new SyntaxError(ERR_UNKNOWN_NAME + fullToken);
}
}
// Switch to the negated form of the referenced Unicode token

@@ -156,3 +172,3 @@ if (item.inverseOf) {

if (!unicode.hasOwnProperty(slug)) {
throw new ReferenceError(`${ERR_UNKNOWN_REF + match[0]} -> ${item.inverseOf}`);
throw new ReferenceError(`${ERR_UNKNOWN_REF + fullToken} -> ${item.inverseOf}`);
}

@@ -164,3 +180,3 @@ item = unicode[slug];

if (!(item.bmp || isAstralMode)) {
throw new SyntaxError(ERR_ASTRAL_ONLY + match[0]);
throw new SyntaxError(ERR_ASTRAL_ONLY + fullToken);
}

@@ -204,2 +220,5 @@ if (isAstralMode) {

* defined as the exact inverse of another token.
* @param {String} [typePrefix] Enables optionally using this type as a prefix for all of the
* provided Unicode tokens, e.g. if given `'Type'`, then `\p{TokenName}` can also be written
* as `\p{Type=TokenName}`.
* @example

@@ -215,6 +234,11 @@ *

*/
XRegExp.addUnicodeData = (data) => {
XRegExp.addUnicodeData = (data, typePrefix) => {
const ERR_NO_NAME = 'Unicode token requires name';
const ERR_NO_DATA = 'Unicode token has no character data ';
if (typePrefix) {
// Case sensitive to match ES2018
unicodeTypes[typePrefix] = {};
}
for (const item of data) {

@@ -227,5 +251,15 @@ if (!item.name) {

}
unicode[normalize(item.name)] = item;
const normalizedName = normalize(item.name);
unicode[normalizedName] = item;
if (typePrefix) {
unicodeTypes[typePrefix][normalizedName] = true;
}
if (item.alias) {
unicode[normalize(item.alias)] = item;
const normalizedAlias = normalize(item.alias);
unicode[normalizedAlias] = item;
if (typePrefix) {
unicodeTypes[typePrefix][normalizedAlias] = true;
}
}

@@ -232,0 +266,0 @@ }

/*!
* XRegExp Unicode Categories 4.4.1
* XRegExp Unicode Categories 5.0.0
* <xregexp.com>

@@ -4,0 +4,0 @@ * Steven Levithan (c) 2010-present MIT License

/*!
* XRegExp Unicode Properties 4.4.1
* XRegExp Unicode Properties 5.0.0
* <xregexp.com>

@@ -4,0 +4,0 @@ * Steven Levithan (c) 2012-present MIT License

/*!
* XRegExp Unicode Scripts 4.4.1
* XRegExp Unicode Scripts 5.0.0
* <xregexp.com>

@@ -25,3 +25,3 @@ * Steven Levithan (c) 2010-present MIT License

XRegExp.addUnicodeData(scripts);
XRegExp.addUnicodeData(scripts, 'Script');
};

@@ -6,3 +6,2 @@ import XRegExp from './xregexp';

import unicodeBase from './addons/unicode-base';
import unicodeBlocks from './addons/unicode-blocks';
import unicodeCategories from './addons/unicode-categories';

@@ -15,3 +14,2 @@ import unicodeProperties from './addons/unicode-properties';

unicodeBase(XRegExp);
unicodeBlocks(XRegExp);
unicodeCategories(XRegExp);

@@ -18,0 +16,0 @@ unicodeProperties(XRegExp);

@@ -27,3 +27,3 @@ // Definitions by: Bart van der Schoor <https://github.com/Bartvds>,

* - `n` - explicit capture
* - `s` - dot matches all (aka singleline)
* - `s` - dot matches all (aka singleline) - works even when not natively supported
* - `x` - free-spacing and line comments (aka extended)

@@ -127,9 +127,11 @@ * - `A` - astral (requires the Unicode Base addon)

* Replacement functions are invoked with three or more arguments:
* - {string} substring - The matched substring (corresponds to `$&` above). Named backreferences are accessible as
* properties of this first argument if the `namespacing` feature is off.
* - {string} args[1..n] - arguments, one for each backreference (corresponding to `$1`, `$2`, etc. above).
* - {number} args[n+1] - The zero-based index of the match within the total search string.
* - {string} args[n+2] - The total string being searched.
* - {XRegExp.NamedGroups} args[n+3] - If the `namespacing` feature is turned on, the last parameter is the groups object. If the
* `namespacing` feature is off, then this argument is not present.
* - {string} args[0] - The matched substring (corresponds to `$&` above). If the `namespacing` feature
* is off, named backreferences are accessible as properties of this argument.
* - {string} args[1..n] - One argument for each backreference (corresponding to `$1`, `$2`, etc. above).
* If the regex has no capturing groups, no arguments appear in this position.
* - {number} args[n+1] - The zero-based index of the match within the entire search string.
* - {string} args[n+2] - The total string being searched.
* - {XRegExp.NamedGroups} args[n+3] - If the the search pattern is a regex with named capturing groups, the last
* argument is the groups object. Its keys are the backreference names and its values are the
* backreference values. If the `namespacing` feature is off, this argument is not present.
*/

@@ -144,15 +146,17 @@ type ReplacementFunction = ((substring: MatchSubString, ...args: Array<string | number | NamedGroupsArray>) => string);

* - `$'` - Inserts the string that follows the matched substring (right context).
* - `$n`, `$nn` - Where n/nn are digits referencing an existent capturing group, inserts
* - `$n`, `$nn` - Where n/nn are digits referencing an existing capturing group, inserts
* backreference n/nn.
* - `${n}`, `$<n>` - Where n is a name or any number of digits that reference an existent capturing
* - `$<n>`, `${n}` - Where n is a name or any number of digits that reference an existing capturing
* group, inserts backreference n.
*
* Replacement functions are invoked with three or more arguments:
* - {string} substring - The matched substring (corresponds to `$&` above). Named backreferences are accessible as
* properties of this first argument if the `namespacing` feature is off.
* - {string} args[1..n] - arguments, one for each backreference (corresponding to `$1`, `$2`, etc. above).
* - {number} args[n+1] - The zero-based index of the match within the total search string.
* - {string} args[n+2] - The total string being searched.
* - {XRegExp.NamedGroups} args[n+3] - If the `namespacing` feature is turned on, the last parameter is the groups object. If the
* `namespacing` feature is off, then this argument is not present.
* - {string} args[0] - The matched substring (corresponds to `$&` above). If the `namespacing` feature
* is off, named backreferences are accessible as properties of this argument.
* - {string} args[1..n] - One argument for each backreference (corresponding to `$1`, `$2`, etc. above).
* If the regex has no capturing groups, no arguments appear in this position.
* - {number} args[n+1] - The zero-based index of the match within the entire search string.
* - {string} args[n+2] - The total string being searched.
* - {XRegExp.NamedGroups} args[n+3] - If the the search pattern is a regex with named capturing groups, the last
* argument is the groups object. Its keys are the backreference names and its values are the
* backreference values. If the `namespacing` feature is off, this argument is not present.
*/

@@ -292,3 +296,3 @@ type ReplacementValue = string | ReplacementFunction;

/**
* Replacement details used in and array for replacing multiple items.
* Replacement details used in an array for replacing multiple items.
*/

@@ -500,2 +504,5 @@ interface ReplacementDetail {

* defined as the exact inverse of another token.
* @param typePrefix - Enables optionally using this type as a prefix for all of the
* provided Unicode tokens, e.g. if given `'Type'`, then `\p{TokenName}` can also be written
* as `\p{Type=TokenName}`.
* @example

@@ -511,3 +518,3 @@ *

*/
function addUnicodeData(data: UnicodeCharacterRange[]): void;
function addUnicodeData(data: UnicodeCharacterRange[], typePrefix?: string): void;

@@ -536,3 +543,3 @@ /**

* time.test('10:59'); // -> true
* XRegExp.exec('10:59', time).minutes; // -> '59'
* XRegExp.exec('10:59', time).groups.minutes; // -> '59'
*/

@@ -550,3 +557,4 @@ function build(pattern: string, subs: Record<string, Pattern>, flags?: string): RegExp;

*
* while (match = XRegExp.cache('.', 'gs').exec(str)) {
* let match;
* while (match = XRegExp.cache('.', 'gs').exec('abc')) {
* // The regex is compiled once only

@@ -559,3 +567,3 @@ * }

* Escapes any regular expression metacharacters, for use when matching literal strings. The result
* can safely be used at any point within a regex that uses any flags.
* can safely be used at any position within a regex that uses any flags.
*

@@ -567,3 +575,3 @@ * @param str - String to escape.

* XRegExp.escape('Escaped? <.>');
* // -> 'Escaped\?\ <\.>'
* // -> 'Escaped\?\u0020<\.>'
*/

@@ -574,7 +582,7 @@ function escape(str: string): string;

* Executes a regex search in a specified string. Returns a match array or `null`. If the provided
* regex uses named capture, named capture groups properties are included on the match array.
* Optional `pos` and `sticky` arguments specify the search start position, and whether the match
* must start at the specified position only. The `lastIndex` property of the provided regex is not
* used, but is updated for compatibility. Also fixes browser bugs compared to the native
* `RegExp.prototype.exec` and can be used reliably cross-browser.
* regex uses named capture, named capture properties are included on the match array's `groups`
* property. Optional `pos` and `sticky` arguments specify the search start position, and whether
* the match must start at the specified position only. The `lastIndex` property of the provided
* regex is not used, but is updated for compatibility. Also fixes browser bugs compared to the
* native `RegExp.prototype.exec` and can be used reliably cross-browser.
*

@@ -586,8 +594,9 @@ * @param str - String to search.

* only. The string `'sticky'` is accepted as an alternative to `true`.
* @returns Match array with named capture groups properties, or `null`.
* @returns Match array with named capture properties on the `groups` object, or `null`. If
* the `namespacing` feature is off, named capture properties are directly on the match array.
* @example
*
* // Basic use, with named capture groups
* // Basic use, with named capturing group
* let match = XRegExp.exec('U+2620', XRegExp('U\\+(?<hex>[0-9A-F]{4})'));
* match.hex; // -> '2620'
* match.groups.hex; // -> '2620'
*

@@ -598,3 +607,3 @@ * // With pos and sticky, in a loop

* result.push(match[1]);
* pos = match.index + match[0].length;
* pos = match.groups.index + match[0].length;
* }

@@ -740,4 +749,4 @@ * // result -> ['2', '3', '4']

* // Passing forward and returning specific backreferences
* html = '<a href="http://xregexp.com/api/">XRegExp</a>\
* <a href="http://www.google.com/">Google</a>';
* const html = `<a href="http://xregexp.com/api/">XRegExp</a>
* <a href="http://www.google.com/">Google</a>`;
* XRegExp.matchChain(html, [

@@ -759,3 +768,3 @@ * {regex: /<a href="([^"]+)">/i, backref: 1},

* @param right - Right delimiter as an XRegExp pattern.
* @param flags - Any native or XRegExp flags, used for the left and right delimiters.
* @param flags - Any combination of XRegExp flags, used for the left and right delimiters.
* @param options - Lets you specify `valueNames` and `escapeChar` options.

@@ -809,5 +818,5 @@ * @returns Array of matches, or an empty array.

* perform a global search and replace, use the optional `scope` argument or include flag g if using
* a regex. Replacement strings can use `${n}` or `$<n>` for named and numbered backreferences.
* Replacement functions can use named backreferences via `arguments[0].name`. Also fixes browser
* bugs compared to the native `String.prototype.replace` and can be used reliably cross-browser.
* a regex. Replacement strings can use `$<n>` or `${n}` for named and numbered backreferences.
* Replacement functions can use named backreferences via the last argument. Also fixes browser bugs
* compared to the native `String.prototype.replace` and can be used reliably cross-browser.
*

@@ -817,4 +826,4 @@ * @param str - String to search.

* @param replacement - Replacement string or a function invoked to create it.
* @param scope - Use 'one' to replace the first match only, or 'all'. If not explicitly specified and using a regex with
* flag g, `scope` is 'all'.
* @param scope - Use 'one' to replace the first match only, or 'all'. Defaults to 'one'.
* Defaults to 'all' if using a regex with flag g.
* @returns New string with one or all matches replaced.

@@ -829,3 +838,6 @@ * @example

* // Regex search, using named backreferences in replacement function
* XRegExp.replace('John Smith', name, (match) => `${match.last as string}, ${match.first as string}`);
* XRegExp.replace('John Smith', name, (...args) => {
* const groups = args[args.length - 1];
* return `${groups.last as string}, ${groups.first as string}`;
* });
* // -> 'Smith, John'

@@ -844,4 +856,4 @@ *

* replacement string or function, and an optional scope of 'one' or 'all'. Uses the XRegExp
* replacement text syntax, which supports named backreference properties via `${name}` or
* `$<name>`.
* replacement text syntax, which supports named backreference properties via `$<name>` or
* `${name}`.
*

@@ -854,3 +866,3 @@ * @param str - String to search.

* str = XRegExp.replaceEach(str, [
* [XRegExp('(?<name>a)'), 'z${name}'],
* [XRegExp('(?<name>a)'), 'z$<name>'],
* [/b/gi, 'y'],

@@ -860,3 +872,3 @@ * [/c/g, 'x', 'one'], // scope 'one' overrides /g

* ['e', 'v', 'all'], // scope 'all' allows replace-all for strings
* [/f/g, ($0) => $0.toUpperCase()]
* [/f/g, (match) => match.toUpperCase()]
* ]);

@@ -907,10 +919,13 @@ */

*
* const h12 = /1[0-2]|0?[1-9]/;
* const h24 = /2[0-3]|[01][0-9]/;
* const hours = XRegExp.tag('x')`${h12} : | ${h24}`;
* const minutes = /^[0-5][0-9]$/;
* // Note that explicitly naming the 'minutes' group is required for named backreferences
* const time = XRegExp.tag('x')`^ ${hours} (?<minutes>${minutes}) $`;
* XRegExp.tag()`\b\w+\b`.test('word'); // -> true
*
* const hours = /1[0-2]|0?[1-9]/;
* const minutes = /(?<minutes>[0-5][0-9])/;
* const time = XRegExp.tag('x')`\b ${hours} : ${minutes} \b`;
* time.test('10:59'); // -> true
* XRegExp.exec('10:59', time).minutes; // -> '59'
* XRegExp.exec('10:59', time).groups.minutes; // -> '59'
*
* const backref1 = /(a)\1/;
* const backref2 = /(b)\1/;
* XRegExp.tag()`${backref1}${backref2}`.test('aabb'); // -> true
*/

@@ -944,4 +959,4 @@ function tag(flags?: string | null): (literals: TemplateStringsArray, ...substitutions: any[]) => RegExp;

/**
* Uninstalls optional features according to the specified options. All optional features start out
* uninstalled, so this is used to undo the actions of `XRegExp.install`.
* Uninstalls optional features according to the specified options. Used to undo the actions of
* `XRegExp.install`.
*

@@ -953,3 +968,3 @@ * @param options - Options object or string.

* XRegExp.uninstall({
* // Disables support for astral code points in Unicode addons
* // Disables support for astral code points in Unicode addons (unless enabled per regex)
* astral: true,

@@ -956,0 +971,0 @@ *

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc