Please support this book: buy it (PDF, EPUB, MOBI) or donate

23. New regular expression features

This chapter explains new regular expression features in ECMAScript 6. It helps if you are familiar with ES5 regular expression features and Unicode. Consult the following two chapters of “Speaking JavaScript” if necessary:

23.1 Overview

The following regular expression features are new in ECMAScript 6:

  • The new flag /y (sticky) anchors each match of a regular expression to the end of the previous match.
  • The new flag /u (unicode) handles surrogate pairs (such as \uD83D\uDE80) as code points and lets you use Unicode code point escapes (such as \u{1F680}) in regular expressions.
  • The new data property flags gives you access to the flags of a regular expression, just like source already gives you access to the pattern in ES5:
  1. > /abc/ig.source // ES5
  2. 'abc'
  3. > /abc/ig.flags // ES6
  4. 'gi'
  • You can use the constructor RegExp() to make a copy of a regular expression:
  1. > new RegExp(/abc/ig).flags
  2. 'gi'
  3. > new RegExp(/abc/ig, 'i').flags // change flags
  4. 'i'

23.2 New flag /y (sticky)

The new flag /y changes two things while matching a regular expression re against a string:

  • Anchored to re.lastIndex: The match must start at re.lastIndex (the index after the previous match). This behavior is similar to the ^ anchor, but with that anchor, matches must always start at index 0.
  • Match repeatedly: If a match was found, re.lastIndex is set to the index after the match. This behavior is similar to the /g flag. Like /g, /y is normally used to match multiple times. The main use case for this matching behavior is tokenizing, where you want each match to immediately follow its predecessor. An example of tokenizing via a sticky regular expression and exec() is given later.

Let’s look at how various regular expression operations react to the /y flag. The following tables give an overview. I’ll provide more details afterwards.

Methods of regular expressions (re is the regular expression that a method is invoked on):

FlagsStart matchingAnchored toResult if matchNo matchre.lastIndex
exec()0Match objectnullunchanged
/gre.lastIndexMatch objectnullindex after match
/yre.lastIndexre.lastIndexMatch objectnullindex after match
/gyre.lastIndexre.lastIndexMatch objectnullindex after match
test()(Any)(like exec())(like exec())truefalse(like exec())

Methods of strings (str is the string that a method is invoked on, r is the regular expression parameter):

FlagsStart matchingAnchored toResult if matchNo matchr.lastIndex
search()–, /g0Index of match-1unchanged
/y, /gy00Index of match-1unchanged
match()0Match objectnullunchanged
/yr.lastIndexr.lastIndexMatch objectnullindex after
match
/gAfter prev.Array with matchesnull0
match (loop)
/gyAfter prev.After prev.Array with matchesnull0
match (loop)match
split()–, /gAfter prev.Array with strings[str]unchanged
match (loop) between matches
/y, /gyAfter prev.After prev.Arr. w/ empty strings[str]unchanged
match (loop)matchbetween matches
replace()0First match replacedNo repl.unchanged
/y00First match replacedNo repl.unchanged
/gAfter prev.All matches replacedNo repl.unchanged
match (loop)
/gyAfter prev.After prev.All matches replacedNo repl.unchanged
match (loop)match

23.2.1 RegExp.prototype.exec(str)

If /g is not set, matching always starts at the beginning, but skips ahead until a match is found. REGEX.lastIndex is not changed.

  1. const REGEX = /a/;
  2.  
  3. REGEX.lastIndex = 7; // ignored
  4. const match = REGEX.exec('xaxa');
  5. console.log(match.index); // 1
  6. console.log(REGEX.lastIndex); // 7 (unchanged)

If /g is set, matching starts at REGEX.lastIndex and skips ahead until a match is found. REGEX.lastIndex is set to the position after the match. That means that you receive all matches if you loop until exec() returns null.

  1. const REGEX = /a/g;
  2.  
  3. REGEX.lastIndex = 2;
  4. const match = REGEX.exec('xaxa');
  5. console.log(match.index); // 3
  6. console.log(REGEX.lastIndex); // 4 (updated)
  7.  
  8. // No match at index 4 or later
  9. console.log(REGEX.exec('xaxa')); // null

If only /y is set, matching starts at REGEX.lastIndex and is anchored to that position (no skipping ahead until a match is found). REGEX.lastIndex is updated similarly to when /g is set.

  1. const REGEX = /a/y;
  2.  
  3. // No match at index 2
  4. REGEX.lastIndex = 2;
  5. console.log(REGEX.exec('xaxa')); // null
  6.  
  7. // Match at index 3
  8. REGEX.lastIndex = 3;
  9. const match = REGEX.exec('xaxa');
  10. console.log(match.index); // 3
  11. console.log(REGEX.lastIndex); // 4

Setting both /y and /g is the same as only setting /y.

23.2.2 RegExp.prototype.test(str)

test() works the same as exec(), but it returns true or false (instead of a match object or null) when matching succeeds or fails:

  1. const REGEX = /a/y;
  2.  
  3. REGEX.lastIndex = 2;
  4. console.log(REGEX.test('xaxa')); // false
  5.  
  6. REGEX.lastIndex = 3;
  7. console.log(REGEX.test('xaxa')); // true
  8. console.log(REGEX.lastIndex); // 4

23.2.3 String.prototype.search(regex)

search() ignores the flag /g and lastIndex (which is not changed, either). Starting at the beginning of the string, it looks for the first match and returns its index (or -1 if there was no match):

  1. const REGEX = /a/;
  2.  
  3. REGEX.lastIndex = 2; // ignored
  4. console.log('xaxa'.search(REGEX)); // 1

If you set the flag /y, lastIndex is still ignored, but the regular expression is now anchored to index 0.

  1. const REGEX = /a/y;
  2.  
  3. REGEX.lastIndex = 1; // ignored
  4. console.log('xaxa'.search(REGEX)); // -1 (no match)

23.2.4 String.prototype.match(regex)

match() has two modes:

  • If /g is not set, it works like exec().
  • If /g is set, it returns an Array with the string parts that matched, or null. If the flag /g is not set, match() captures groups like exec():
  1. {
  2. const REGEX = /a/;
  3.  
  4. REGEX.lastIndex = 7; // ignored
  5. console.log('xaxa'.match(REGEX).index); // 1
  6. console.log(REGEX.lastIndex); // 7 (unchanged)
  7. }
  8. {
  9. const REGEX = /a/y;
  10.  
  11. REGEX.lastIndex = 2;
  12. console.log('xaxa'.match(REGEX)); // null
  13.  
  14. REGEX.lastIndex = 3;
  15. console.log('xaxa'.match(REGEX).index); // 3
  16. console.log(REGEX.lastIndex); // 4
  17. }

If only the flag /g is set then match() returns all matching substrings in an Array (or null). Matching always starts at position 0.

  1. const REGEX = /a|b/g;
  2. REGEX.lastIndex = 7;
  3. console.log('xaxb'.match(REGEX)); // ['a', 'b']
  4. console.log(REGEX.lastIndex); // 0

If you additionally set the flag /y, then matching is still performed repeatedly, while anchoring the regular expression to the index after the previous match (or 0).

  1. const REGEX = /a|b/gy;
  2.  
  3. REGEX.lastIndex = 0; // ignored
  4. console.log('xab'.match(REGEX)); // null
  5. REGEX.lastIndex = 1; // ignored
  6. console.log('xab'.match(REGEX)); // null
  7.  
  8. console.log('ab'.match(REGEX)); // ['a', 'b']
  9. console.log('axb'.match(REGEX)); // ['a']

23.2.5 String.prototype.split(separator, limit)

The complete details of split() are explained in Speaking JavaScript.

For ES6, it is interesting to see how things change if you use the flag /y.

With /y, the string must start with a separator:

  1. > 'x##'.split(/#/y) // no match
  2. [ 'x##' ]
  3. > '##x'.split(/#/y) // 2 matches
  4. [ '', '', 'x' ]

Subsequent separators are only recognized if they immediately follow the first separator:

  1. > '#x#'.split(/#/y) // 1 match
  2. [ '', 'x#' ]
  3. > '##'.split(/#/y) // 2 matches
  4. [ '', '', '' ]

That means that the string before the first separator and the strings between separators are always empty.

As usual, you can use groups to put parts of the separators into the result array:

  1. > '##'.split(/(#)/y)
  2. [ '', '#', '', '#', '' ]

23.2.6 String.prototype.replace(search, replacement)

Without the flag /g, replace() only replaces the first match:

  1. const REGEX = /a/;
  2.  
  3. // One match
  4. console.log('xaxa'.replace(REGEX, '-')); // 'x-xa'

If only /y is set, you also get at most one match, but that match is always anchored to the beginning of the string. lastIndex is ignored and unchanged.

  1. const REGEX = /a/y;
  2.  
  3. // Anchored to beginning of string, no match
  4. REGEX.lastIndex = 1; // ignored
  5. console.log('xaxa'.replace(REGEX, '-')); // 'xaxa'
  6. console.log(REGEX.lastIndex); // 1 (unchanged)
  7.  
  8. // One match
  9. console.log('axa'.replace(REGEX, '-')); // '-xa'

With /g set, replace() replaces all matches:

  1. const REGEX = /a/g;
  2.  
  3. // Multiple matches
  4. console.log('xaxa'.replace(REGEX, '-')); // 'x-x-'

With /gy set, replace() replaces all matches, but each match is anchored to the end of the previous match:

  1. const REGEX = /a/gy;
  2.  
  3. // Multiple matches
  4. console.log('aaxa'.replace(REGEX, '-')); // '--xa'

The parameter replacement can also be a function, consult “Speaking JavaScript” for details.

23.2.7 Example: using sticky matching for tokenizing

The main use case for sticky matching is tokenizing, turning a text into a sequence of tokens. One important trait about tokenizing is that tokens are fragments of the text and that there must be no gaps between them. Therefore, sticky matching is perfect here.

  1. function tokenize(TOKEN_REGEX, str) {
  2. const result = [];
  3. let match;
  4. while (match = TOKEN_REGEX.exec(str)) {
  5. result.push(match[1]);
  6. }
  7. return result;
  8. }
  9.  
  10. const TOKEN_GY = /\s*(\+|[0-9]+)\s*/gy;
  11. const TOKEN_G = /\s*(\+|[0-9]+)\s*/g;

In a legal sequence of tokens, sticky matching and non-sticky matching produce the same output:

  1. > tokenize(TOKEN_GY, '3 + 4')
  2. [ '3', '+', '4' ]
  3. > tokenize(TOKEN_G, '3 + 4')
  4. [ '3', '+', '4' ]

If, however, there is non-token text in the string then sticky matching stops tokenizing, while non-sticky matching skips the non-token text:

  1. > tokenize(TOKEN_GY, '3x + 4')
  2. [ '3' ]
  3. > tokenize(TOKEN_G, '3x + 4')
  4. [ '3', '+', '4' ]

The behavior of sticky matching during tokenizing helps with error handling.

23.2.8 Example: manually implementing sticky matching

If you wanted to manually implement sticky matching, you’d do it as follows: The function execSticky() works like RegExp.prototype.exec() in sticky mode.

  1. function execSticky(regex, str) {
  2. // Anchor the regex to the beginning of the string
  3. let matchSource = regex.source;
  4. if (!matchSource.startsWith('^')) {
  5. matchSource = '^' + matchSource;
  6. }
  7. // Ensure that instance property `lastIndex` is updated
  8. let matchFlags = regex.flags; // ES6 feature!
  9. if (!regex.global) {
  10. matchFlags = matchFlags + 'g';
  11. }
  12. const matchRegex = new RegExp(matchSource, matchFlags);
  13.  
  14. // Ensure we start matching `str` at `regex.lastIndex`
  15. const matchOffset = regex.lastIndex;
  16. const matchStr = str.slice(matchOffset);
  17. let match = matchRegex.exec(matchStr);
  18.  
  19. // Translate indices from `matchStr` to `str`
  20. regex.lastIndex = matchRegex.lastIndex + matchOffset;
  21. match.index = match.index + matchOffset;
  22. return match;
  23. }

23.3 New flag /u (unicode)

The flag /u switches on a special Unicode mode for a regular expression. That mode has two features:

  • You can use Unicode code point escape sequences such as \u{1F42A} for specifying characters via code points. Normal Unicode escapes such as \u03B1 only have a range of four hexadecimal digits (which equals the basic multilingual plane).
  • “characters” in the regular expression pattern and the string are code points (not UTF-16 code units). Code units are converted into code points. A section in the chapter on Unicode has more information on escape sequences. I’ll explain the consequences of feature 2 next. Instead of Unicode code point escapes (e.g., \u{1F680}), I’m using two UTF-16 code units (e.g., \uD83D\uDE80). That makes it clear that surrogate pairs are grouped in Unicode mode and works in both Unicode mode and non-Unicode mode.
  1. > '\u{1F680}' === '\uD83D\uDE80' // code point vs. surrogate pairs
  2. true

23.3.1 Consequence: lone surrogates in the regular expression only match lone surrogates

In non-Unicode mode, a lone surrogate in a regular expression is even found inside (surrogate pairs encoding) code points:

  1. > /\uD83D/.test('\uD83D\uDC2A')
  2. true

In Unicode mode, surrogate pairs become atomic units and lone surrogates are not found “inside” them:

  1. > /\uD83D/u.test('\uD83D\uDC2A')
  2. false

Actual lone surrogate are still found:

  1. > /\uD83D/u.test('\uD83D \uD83D\uDC2A')
  2. true
  3. > /\uD83D/u.test('\uD83D\uDC2A \uD83D')
  4. true

23.3.2 Consequence: you can put code points in character classes

In Unicode mode, you can put code points into character classes and they won’t be interpreted as two characters, anymore.

  1. > /^[\uD83D\uDC2A]$/u.test('\uD83D\uDC2A')
  2. true
  3. > /^[\uD83D\uDC2A]$/.test('\uD83D\uDC2A')
  4. false
  5.  
  6. > /^[\uD83D\uDC2A]$/u.test('\uD83D')
  7. false
  8. > /^[\uD83D\uDC2A]$/.test('\uD83D')
  9. true

23.3.3 Consequence: the dot operator (.) matches code points, not code units

In Unicode mode, the dot operator matches code points (one or two code units). In non-Unicode mode, it matches single code units. For example:

  1. > '\uD83D\uDE80'.match(/./gu).length
  2. 1
  3. > '\uD83D\uDE80'.match(/./g).length
  4. 2

23.3.4 Consequence: quantifiers apply to code points, not code units

In Unicode mode, quantifiers apply to code points (one or two code units). In non-Unicode mode, they apply to single code units. For example:

  1. > /\uD83D\uDE80{2}/u.test('\uD83D\uDE80\uD83D\uDE80')
  2. true
  3.  
  4. > /\uD83D\uDE80{2}/.test('\uD83D\uDE80\uD83D\uDE80')
  5. false
  6. > /\uD83D\uDE80{2}/.test('\uD83D\uDE80\uDE80')
  7. true

23.4 New data property flags

In ECMAScript 6, regular expressions have the following data properties:

  • The pattern: source
  • The flags: flags
  • Individual flags: global, ignoreCase, multiline, sticky, unicode
  • Other: lastIndex As an aside, lastIndex is the only instance property now, all other data properties are implemented via internal instance properties and getters such as get RegExp.prototype.global.

The property source (which already existed in ES5) contains the regular expression pattern as a string:

  1. > /abc/ig.source
  2. 'abc'

The property flags is new, it contains the flags as a string, with one character per flag:

  1. > /abc/ig.flags
  2. 'gi'

You can’t change the flags of an existing regular expression (ignoreCase etc. have always been immutable), but flags allows you to make a copy where the flags are changed:

  1. function copyWithIgnoreCase(re) {
  2. return new RegExp(re.source,
  3. re.flags.includes('i') ? re.flags : re.flags+'i');
  4. }

The next section explains another way to make modified copies of regular expressions.

23.5 RegExp() can be used as a copy constructor

In ES6 there are two variants of the constructor RegExp() (the second one is new):

  • new RegExp(pattern : string, flags = '')A new regular expression is created as specified via pattern. If flags is missing, the empty string '' is used.
  • new RegExp(regex : RegExp, flags = regex.flags)regex is cloned. If flags is provided then it determines the flags of the copy. The following interaction demonstrates the latter variant:
  1. > new RegExp(/abc/ig).flags
  2. 'gi'
  3. > new RegExp(/abc/ig, 'i').flags // change flags
  4. 'i'

Therefore, the RegExp constructor gives us another way to change flags:

  1. function copyWithIgnoreCase(re) {
  2. return new RegExp(re,
  3. re.flags.includes('i') ? re.flags : re.flags+'i');
  4. }

23.5.1 Example: an iterable version of exec()

The following function execAll() is an iterable version of exec() that fixes several issues with using exec() to retrieve all matches of a regular expression:

  • Looping over the matches is unnecessarily complicated (you call exec() until it returns null).
  • exec() mutates the regular expression, which means that side effects can become a problem.
  • The flag /g must be set. Otherwise, only the first match is returned.
  1. function* execAll(regex, str) {
  2. // Make sure flag /g is set and regex.index isn’t changed
  3. const localCopy = copyAndEnsureFlag(regex, 'g');
  4. let match;
  5. while (match = localCopy.exec(str)) {
  6. yield match;
  7. }
  8. }
  9. function copyAndEnsureFlag(re, flag) {
  10. return new RegExp(re,
  11. re.flags.includes(flag) ? re.flags : re.flags+flag);
  12. }

Using execAll():

  1. const str = '"fee" "fi" "fo" "fum"';
  2. const regex = /"([^"]*)"/;
  3.  
  4. // Access capture of group #1 via destructuring
  5. for (const [, group1] of execAll(regex, str)) {
  6. console.log(group1);
  7. }
  8. // Output:
  9. // fee
  10. // fi
  11. // fo
  12. // fum

23.6 String methods that delegate to regular expression methods

The following string methods now delegate some of their work to regular expression methods:

  • String.prototype.match calls RegExp.prototype[Symbol.match].
  • String.prototype.replace calls RegExp.prototype[Symbol.replace].
  • String.prototype.search calls RegExp.prototype[Symbol.search].
  • String.prototype.split calls RegExp.prototype[Symbol.split]. For more information, consult Sect. “String methods that delegate regular expression work to their parameters” in the chapter on strings.

Further reading

If you want to know in more detail how the regular expression flag /u works, I recommend the article “Unicode-aware regular expressions in ECMAScript 6” by Mathias Bynens.