CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-xregexp

Extended regular expressions with augmented syntax, named capture groups, Unicode support, and cross-browser compatibility

Overview
Eval results
Files

string-processing.mddocs/

String Processing Methods

Enhanced string methods with named backreference support and cross-browser fixes.

Capabilities

Enhanced Match Method

Enhanced match method with scope control and consistent return types.

/**
 * Enhanced match method with scope control
 * @param str - String to search
 * @param regex - Regex to search with
 * @param scope - Use 'one' to return first match as string, 'all' for array of all matches
 * @returns In match-first mode: first match as string or null. In match-all mode: array of matches or empty array
 */
function match(str: string, regex: RegExp, scope?: 'one' | 'all'): string | string[] | null;

Usage Examples:

// Match first occurrence
XRegExp.match('abc', /\\w/); // 'a'
XRegExp.match('abc', /\\w/g, 'one'); // 'a' (overrides global flag)
XRegExp.match('abc', /x/g, 'one'); // null

// Match all occurrences
XRegExp.match('abc', /\\w/g); // ['a', 'b', 'c']
XRegExp.match('abc', /\\w/, 'all'); // ['a', 'b', 'c'] (forces match-all)
XRegExp.match('abc', /x/, 'all'); // [] (empty array instead of null)

Enhanced Replace Method

Enhanced replace with named backreference support and improved replacement syntax.

/**
 * Enhanced replace with named backreference support
 * @param str - String to search
 * @param search - Search pattern to be replaced (string or regex)
 * @param replacement - Replacement string or function
 * @param scope - Use 'one' to replace first match only, 'all' for global replacement
 * @returns New string with one or all matches replaced
 */
function replace(str: string, search: string | RegExp, replacement: string | Function, scope?: 'one' | 'all'): string;

Named Backreference Syntax:

  • $<name> or ${name} - Named backreferences
  • $1, $2, etc. - Numbered backreferences
  • $& or $0 - Full match
  • $$ - Literal dollar sign
  • `$`` - Left context (text before match)
  • $' - Right context (text after match)

Usage Examples:

// Named backreferences in replacement string
const nameRegex = XRegExp('(?<first>\\\\w+) (?<last>\\\\w+)');
XRegExp.replace('John Smith', nameRegex, '$<last>, $<first>');
// Result: 'Smith, John'

// Named backreferences in replacement function
XRegExp.replace('John Smith', nameRegex, (...args) => {
  const groups = args[args.length - 1];
  return `${groups.last}, ${groups.first}`;
});
// Result: 'Smith, John'

// String search with replace-all
XRegExp.replace('RegExp builds RegExps', 'RegExp', 'XRegExp', 'all');
// Result: 'XRegExp builds XRegExps'

// Scope control
XRegExp.replace('test test test', /test/g, 'X', 'one'); // 'X test test'
XRegExp.replace('test test test', /test/, 'X', 'all');  // 'X X X'

Batch Replace Method

Performs batch processing of string replacements.

/**
 * Performs batch processing of string replacements
 * @param str - String to search
 * @param replacements - Array of replacement detail arrays [search, replacement, scope?]
 * @returns New string with all replacements applied
 */
function replaceEach(str: string, replacements: [string | RegExp, string | Function, ('one' | 'all')?][]): string;

Usage Examples:

const result = XRegExp.replaceEach('abcdef', [
  [XRegExp('(?<name>a)'), 'z$<name>'],           // 'zabcdef'
  [/b/gi, 'y'],                                 // 'zaydef'
  [/c/g, 'x', 'one'],                          // 'zayxdef' (scope overrides /g)
  [/d/, 'w', 'all'],                           // 'zaywxef' (scope adds global)
  ['e', 'v', 'all'],                           // 'zaywxvf'
  [/f/g, (match) => match.toUpperCase()]       // 'zaywxvF'
]);

Enhanced Split Method

Enhanced split method with cross-browser fixes and backreference support.

/**
 * Enhanced split method with cross-browser fixes
 * @param str - String to split
 * @param separator - Regex or string to use for separating
 * @param limit - Maximum number of items to include in result array
 * @returns Array of substrings
 */
function split(str: string, separator: string | RegExp, limit?: number): string[];

Usage Examples:

// Basic usage
XRegExp.split('a b c', ' '); // ['a', 'b', 'c']

// With limit
XRegExp.split('a b c', ' ', 2); // ['a', 'b']

// Backreferences in result array
XRegExp.split('..word1..', /([a-z]+)(\\d+)/i);
// Result: ['..', 'word', '1', '..']

// Cross-browser consistent behavior
XRegExp.split('a,,b', /,/); // Always ['a', '', 'b'] regardless of browser

Named Backreferences in Replacements

Replacement String Syntax

XRegExp extends standard replacement syntax with named backreferences:

const phoneRegex = XRegExp('(?<area>\\\\d{3})-(?<exchange>\\\\d{3})-(?<number>\\\\d{4})');
const phone = '555-123-4567';

// Standard numbered backreferences
XRegExp.replace(phone, phoneRegex, '($1) $2-$3');
// Result: '(555) 123-4567'

// Named backreferences with angle brackets
XRegExp.replace(phone, phoneRegex, '($<area>) $<exchange>-$<number>');
// Result: '(555) 123-4567'

// Named backreferences with curly braces
XRegExp.replace(phone, phoneRegex, '(${area}) ${exchange}-${number}');
// Result: '(555) 123-4567'

Replacement Functions

Named captures are passed to replacement functions:

const dateRegex = XRegExp('(?<year>\\\\d{4})-(?<month>\\\\d{2})-(?<day>\\\\d{2})');

XRegExp.replace('2021-02-22', dateRegex, (match, year, month, day, index, string, groups) => {
  // With namespacing enabled (default in XRegExp 5+):
  // groups.year, groups.month, groups.day
  return `${groups.month}/${groups.day}/${groups.year}`;
});

// Without namespacing (legacy mode):
XRegExp.uninstall('namespacing');
XRegExp.replace('2021-02-22', dateRegex, (match, year, month, day, index, string) => {
  // Named properties directly on match object
  return `${match.month}/${match.day}/${match.year}`;
});

Cross-browser Consistency

XRegExp string methods provide consistent behavior across browsers:

Replacement Text Handling

Properly handles replacement text edge cases:

// Consistent handling of special replacement sequences
XRegExp.replace('test', /e/, '$&$&'); // Always 'teest'
XRegExp.replace('test', /e/, '$$');   // Always 'te$t'

Split Edge Cases

Handles split edge cases consistently:

// Consistent empty string handling
XRegExp.split('abc', /(?=)/); // Consistent results across browsers

// Proper limit handling
XRegExp.split('a-b-c', /-/, 2); // Always ['a', 'b']

Match Type Consistency

Provides predictable return types:

// XRegExp.match always returns arrays for match-all, strings/null for match-first
const result1 = XRegExp.match('abc', /\\w/, 'all'); // Always array ['a', 'b', 'c']
const result2 = XRegExp.match('abc', /x/, 'all');   // Always array []
const result3 = XRegExp.match('abc', /\\w/);        // Always string 'a' or null

Install with Tessl CLI

npx tessl i tessl/npm-xregexp

docs

advanced-matching.md

construction.md

execution.md

extensibility.md

index.md

pattern-building.md

string-processing.md

unicode-support.md

tile.json