constructor - JavaScript

constructor
===========

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

* Learn more
* See full compatibility
* Report feedback
The **`constructor`** method is a special method of a class for creating and initializing an object instance of that class.

**Note:** This page introduces the `constructor` syntax. For the `constructor` property present on all objects, see `Object.prototype.constructor`.

Try it
------

Syntax
------

```js
constructor() { /\* … \*/ }
constructor(argument0) { /\* … \*/ }
constructor(argument0, argument1) { /\* … \*/ }
constructor(argument0, argument1, /\* …, \*/ argumentN) { /\* … \*/ }
```

There are some additional syntax restrictions:

* A class method called `constructor` cannot be a getter, setter, async, or generator.
* A class cannot have more than one `constructor` method.
Description
-----------

A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.

```js
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
```

 If you don't provide your own constructor, then a default constructor will be supplied for you.
 If your class is a base class, the default constructor is empty:

```js
constructor() {}
```

If your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided:

```js
constructor(...args) {
  super(...args);
}
```

**Note:** The difference between an explicit constructor like the one above and the default constructor is that the latter doesn't actually invoke the array iterator through argument spreading.

That enables code like this to work:

```js
class ValidationError extends Error {
  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // This is Error instead of ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
```

 The `ValidationError` class doesn't need an explicit constructor, because it doesn't need to do any custom initialization.
 The default constructor then takes care of initializing the parent `Error` from the argument it is given.

 However, if you provide your own constructor, and your class derives from some parent class, then you must explicitly call the parent class constructor using `super()`.
 For example:

```js
class ValidationError extends Error {
  constructor(message) {
    super(message); // call parent class constructor
    this.name = "ValidationError";
    this.code = "42";
  }

  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // Now this is ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
```

Using `new` on a class goes through the following steps:

1. (If it's a derived class) The `constructor` body before the `super()` call is evaluated. This part should not access `this` because it's not yet initialized.
2. (If it's a derived class) The `super()` call is evaluated, which initializes the parent class through the same process.
3. The current class's fields are initialized.
4. The `constructor` body after the `super()` call (or the entire body, if it's a base class) is evaluated.

Within the `constructor` body, you can access the object being created through `this` and access the class that is called with `new` through `new.target`. Note that methods (including getters and setters) and the prototype chain are already initialized on `this` before the `constructor` is executed, so you can even access methods of the subclass from the constructor of the superclass. However, if those methods use `this`, the `this` will not have been fully initialized yet. This means reading public fields of the derived class will result in `undefined`, while reading private fields will result in a `TypeError`.

```js
new (class C extends class B {
  constructor() {
    console.log(this.foo());
  }
} {
  #a = 1;
  foo() {
    return this.#a; // TypeError: Cannot read private member #a from an object whose class did not declare it
    // It's not really because the class didn't declare it,
    // but because the private field isn't initialized yet
    // when the superclass constructor is running
  }
})();
```

The `constructor` method may have a return value. While the base class may return anything from its constructor, the derived class must return an object or `undefined`, or a `TypeError` will be thrown.

```js
class ParentClass {
  constructor() {
    return 1;
  }
}

console.log(new ParentClass()); // ParentClass {}
// The return value is ignored because it's not an object
// This is consistent with function constructors

class ChildClass extends ParentClass {
  constructor() {
    return 1;
  }
}

console.log(new ChildClass()); // TypeError: Derived constructors may only return object or undefined
```

If the parent class constructor returns an object, that object will be used as the `this` value on which class fields of the derived class will be defined. This trick is called "return overriding", which allows a derived class's fields (including private ones) to be defined on unrelated objects.

The `constructor` follows normal method syntax, so parameter default values, rest parameters, etc. can all be used.

```js
class Person {
  constructor(name = "Anonymous") {
    this.name = name;
  }
  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const person = new Person();
person.introduce(); // Hello, my name is Anonymous
```

The constructor must be a literal name. Computed properties cannot become constructors.

```js
class Foo {
  // This is a computed property. It will not be picked up as a constructor.
  ["constructor"]() {
    console.log("called");
    this.a = 1;
  }
}

const foo = new Foo(); // No log
console.log(foo); // Foo {}
foo.constructor(); // Logs "called"
console.log(foo); // Foo { a: 1 }
```

Async methods, generator methods, accessors, and class fields are forbidden from being called `constructor`. Private names cannot be called `#constructor`. Any member named `constructor` must be a plain method.

Examples
--------

### Using the constructor

This code snippet is taken from the classes sample (live demo).

```js
class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // NOTE: In derived classes, `super()` must be called before you
    // can use `this`. Leaving this out will cause a ReferenceError.
    this.name = "Square";
  }

  get area() {
    return this.height \* this.width;
  }

  set area(value) {
    this.height = value \*\* 0.5;
    this.width = value \*\* 0.5;
  }
}
```

### Calling super in a constructor bound to a different prototype

`super()` calls the constructor that's the prototype of the current class. If you change the prototype of the current class itself, `super()` will call the constructor that's the new prototype. Changing the prototype of the current class's `prototype` property doesn't affect which constructor `super()` calls.

```js
class Polygon {
  constructor() {
    this.name = "Polygon";
  }
}

class Rectangle {
  constructor() {
    this.name = "Rectangle";
  }
}

class Square extends Polygon {
  constructor() {
    super();
  }
}

// Make Square extend Rectangle (which is a base class) instead of Polygon
Object.setPrototypeOf(Square, Rectangle);

const newInstance = new Square();

// newInstance is still an instance of Polygon, because we didn't
// change the prototype of Square.prototype, so the prototype chain
// of newInstance is still
// newInstance --> Square.prototype --> Polygon.prototype
console.log(newInstance instanceof Polygon); // true
console.log(newInstance instanceof Rectangle); // false

// However, because super() calls Rectangle as constructor, the name property
// of newInstance is initialized with the logic in Rectangle
console.log(newInstance.name); // Rectangle
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-static-semantics-constructormethod |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using classes guide
* Classes
* Static initialization blocks
* `class`
* `super()`
* `Object.prototype.constructor`


Lookahead assertion: (?=...), (?!...) - JavaScript

Lookahead assertion: (?=...), (?!...)
=====================================

A **lookahead assertion** "looks ahead": it attempts to match the subsequent input with the given pattern, but it does not consume any of the input — if the match is successful, the current position in the input stays the same.

Syntax
------

```regex
(?=pattern)
(?!pattern)
```

### Parameters

`pattern`

A pattern consisting of anything you may use in a regex literal, including a disjunction.

Description
-----------

A regular expression generally matches from left to right. This is why lookahead and lookbehind assertions are called as such — lookahead asserts what's on the right, and lookbehind asserts what's on the left.

In order for a `(?=pattern)` assertion to succeed, the `pattern` must match the text after the current position, but the current position is not changed. The `(?!pattern)` form negates the assertion — it succeeds if the `pattern` does not match at the current position.

The `pattern` can contain capturing groups. See the capturing groups page for more information on the behavior in this case.

Unlike other regular expression operators, there's no backtracking into a lookahead — this behavior is inherited from Perl. This only matters when the `pattern` contains capturing groups and the pattern following the lookahead contains backreferences to those captures. For example:

```js
/(?=(a+))a\*b\1/.exec("baabac"); // ['aba', 'a']
// Not ['aaba', 'a']
```

The matching of the pattern above happens as follows:

1. The lookahead `(a+)` succeeds before the first `"a"` in `"baabac"`, and `"aa"` is captured because the quantifier is greedy.
2. `a*b` matches the `"aab"` in `"baabac"` because lookaheads don't consume their matched strings.
3. `\1` does not match the following string, because that requires 2 `"a"`s, but only 1 is available. So the matcher backtracks, but it doesn't go into the lookahead, so the capturing group cannot be reduced to 1 `"a"`, and the entire match fails at this point.
4. `exec()` re-attempts matching at the next position — before the second `"a"`. This time, the lookahead matches `"a"`, and `a*b` matches `"ab"`. The backreference `\1` matches the captured `"a"`, and the match succeeds.

If the regex is able to backtrack into the lookahead and revise the choice made in there, then the match would succeed at step 3 by `(a+)` matching the first `"a"` (instead of the first two `"a"`s) and `a*b` matching `"aab"`, without even re-attempting the next input position.

Negative lookaheads can contain capturing groups as well, but backreferences only make sense within the `pattern`, because if matching continues, `pattern` would necessarily be unmatched (otherwise the assertion fails). This means outside of the `pattern`, backreferences to those capturing groups in negative lookaheads always succeed. For example:

```js
/(.\*?)a(?!(a+)b\2c)\2(.\*)/.exec("baaabaac"); // ['baaabaac', 'ba', undefined, 'abaac']
```

The matching of the pattern above happens as follows:

1. The `(.*?)` pattern is non-greedy, so it starts by matching nothing. However, the next character is `a`, which fails to match `"b"` in the input.
2. The `(.*?)` pattern matches `"b"` so that the `a` in the pattern matches the first `"a"` in `"baaabaac"`.
3. At this position, the lookahead succeeds to match, because if `(a+)` matches `"aa"`, then `(a+)b\2c` matches `"aabaac"`. This causes the assertion to fail, so the matcher backtracks.
4. The `(.*?)` pattern matches the `"ba"` so that the `a` in the pattern matches the second `"a"` in `"baaabaac"`.
5. At this position, the lookahead fails to match, because the remaining input does not follow the pattern "any number of `"a"`s, a `"b"`, the same number of `"a"`s, a `c`". This causes the assertion to succeed.
6. However, because nothing was matched within the assertion, the `\2` backreference has no value, so it matches the empty string. This causes the rest of the input to be consumed by the `(.*)` at the end.

Normally, assertions cannot be quantified. However, in Unicode-unaware mode, lookahead assertions can be quantified. This is a deprecated syntax for web compatibility, and you should not rely on it.

```js
/(?=a)?b/.test("b"); // true; the lookahead is matched 0 time
```

Examples
--------

### Matching strings without consuming them

Sometimes it's useful to validate that the matched string is followed by something without returning that as the result. The following example matches a string that is followed by a comma/period, but the punctuation is not included in the result:

```js
function getFirstSubsentence(str) {
  return /^.\*?(?=[,.])/.exec(str)?.[0];
}

getFirstSubsentence("Hello, world!"); // "Hello"
getFirstSubsentence("Thank you."); // "Thank you"
```

A similar effect can be achieved by capturing the submatch you are interested in.

### Pattern subtraction and intersection

Using lookahead, you can match a string multiple times with different patterns, which allows you to express complex relationships like subtraction (is X but not Y) and intersection (is both X and Y).

The following example matches any identifier that's not a reserved word (only showing three reserved words here for brevity; more reserved words can be added to this disjunction). The `[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*` syntax describes exactly the set of identifier strings in the language spec; you can read more about identifiers in lexical grammar and the `\p` escape in Unicode character class escape.

```js
function isValidIdentifierName(str) {
  const re =
    /^(?!(?:break|case|catch)$)[$\_\p{ID\_Start}][$\u200c\u200d\p{ID\_Continue}]\*$/u;
  return re.test(str);
}

isValidIdentifierName("break"); // false
isValidIdentifierName("foo"); // true
isValidIdentifierName("cases"); // true
```

The following example matches a string that's both ASCII and can be used as an identifier part:

```js
function isASCIIIDPart(char) {
  return /^(?=\p{ASCII}$)\p{ID\_Start}$/u.test(char);
}

isASCIIIDPart("a"); // true
isASCIIIDPart("α"); // false
isASCIIIDPart(":"); // false
```

If you are doing intersection and subtraction with finitely many characters, you may want to use the character set intersection syntax enabled with the `v` flag.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Assertion |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Assertions guide
* Regular expressions
* Input boundary assertion: `^`, `$`
* Word boundary assertion: `\b`, `\B`
* Lookbehind assertion: `(?<=...)`, `(?<!...)`
* Capturing group: `(...)`


Non-capturing group: (?:...) - JavaScript

Non-capturing group: (?:...)
============================

A **non-capturing group** groups a subpattern, allowing you to apply a quantifier to the entire group or use disjunctions within it. It acts like the grouping operator in JavaScript expressions, and unlike capturing groups, it does not memorize the matched text, allowing for better performance and avoiding confusion when the pattern also contains useful capturing groups.

Syntax
------

```regex
(?:pattern)
```

### Parameters

`pattern`

A pattern consisting of anything you may use in a regex literal, including a disjunction.

Examples
--------

### Grouping a subpattern and applying a quantifier

In the following example, we test if a file path ends with `styles.css` or `styles.[a hex hash].css`. Because the entire `\.[\da-f]+` part is optional, in order to apply the `?` quantifier to it, we need to group it into a new atom. Using a non-capturing group improves performance by not creating the extra match information that we don't need.

```js
function isStylesheet(path) {
  return /styles(?:\.[\da-f]+)?\.css$/.test(path);
}

isStylesheet("styles.css"); // true
isStylesheet("styles.1234.css"); // true
isStylesheet("styles.cafe.css"); // true
isStylesheet("styles.1234.min.css"); // false
```

### Grouping a disjunction

A disjunction has the lowest precedence in a regular expression. If you want to use a disjunction as a part of a bigger pattern, you must group it. You are advised to use a non-capturing group unless you rely on the matched text of the disjunction. The following example matches file extensions, using the same code as the input boundary assertion article:

```js
function isImage(filename) {
  return /\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);
}

isImage("image.png"); // true
isImage("image.jpg"); // true
isImage("image.pdf"); // false
```

### Avoiding refactoring hazards

Capturing groups are accessed by their position in the pattern. If you add or remove a capturing group, you must also update the positions of the other capturing groups, if you are accessing them through match results or backreferences. This can be a source of bugs, especially if most groups are purely for syntactic purposes (to apply quantifiers or to group disjunctions). Using non-capturing groups avoids this problem, and allows the indices of actual capturing groups to be easily tracked.

For example, suppose we have a function that matches the `title='xxx'` pattern in a string (example taken from capturing group). To ensure the quotes match, we use a backreference to refer to the first quote.

```js
function parseTitle(metastring) {
  return metastring.match(/title=(["'])(.\*?)\1/)[2];
}

parseTitle('title="foo"'); // 'foo'
```

If we later decided to add `name='xxx'` as an alias for `title=`, we will need to group the disjunction in another group:

```js
function parseTitle(metastring) {
  // Oops — the backreference and index access are now off by one!
  return metastring.match(/(title|name)=(["'])(.\*?)\1/)[2];
}

parseTitle('name="foo"'); // Cannot read properties of null (reading '2')
// Because \1 now refers to the "name" string, which isn't found at the end.
```

Instead of locating all places where we are referring to the capturing groups' indices and updating them one-by-one, it's better to avoid using a capturing group:

```js
function parseTitle(metastring) {
  // Do not capture the title|name disjunction
  // because we don't use its value
  return metastring.match(/(?:title|name)=(["'])(.\*?)\1/)[2];
}

parseTitle('name="foo"'); // 'foo'
```

Named capturing groups are another way to avoid refactoring hazards. It allows capturing groups to accessed by a custom name, which is unaffected when other capturing groups are added or removed.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Atom |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Groups and backreferences guide
* Regular expressions
* Capturing group: `(...)`
* Named capturing group: `(?<name>...)`


Word boundary assertion: \b, \B - JavaScript

Word boundary assertion: \b, \B
===============================

A **word boundary assertion** checks if the current position in the string is a word boundary. A word boundary is where the next character is a word character and the previous character is not a word character, or vice versa.

Syntax
------

```regex
\b
\B
```

Description
-----------

`\b` asserts that the current position in the string is a word boundary. `\B` negates the assertion: it asserts that the current position is not a word boundary. Both are *assertions*, so unlike other character escapes or character class escapes, `\b` and `\B` don't consume any characters.

A word character includes the following:

* Letters (A–Z, a–z), numbers (0–9), and underscore (\_).
* If the regex is Unicode-aware and the `i` flag is set, other Unicode characters that get canonicalized to one of the characters above through case folding.

Word characters are also matched by the `\w` character class escape.

Out-of-bounds input positions are considered non-word characters. For example, the following are successful matches:

```js
/\ba/.exec("abc");
/c\b/.exec("abc");

/\B /.exec(" abc");
/ \B/.exec("abc ");
```

Examples
--------

### Detecting words

The following example detects if a string contains the word "thanks" or "thank you":

```js
function hasThanks(str) {
  return /\b(thanks|thank you)\b/i.test(str);
}

hasThanks("Thanks! You helped me a lot."); // true
hasThanks("Just want to say thank you for all your work."); // true
hasThanks("Thanksgiving is around the corner."); // false
```

**Warning:** Not all languages have clearly defined word boundaries. If you are working with languages like Chinese or Thai, where there are no whitespace separators, use a more advanced library like `Intl.Segmenter` to search for words instead.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Assertion |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Assertions guide
* Regular expressions
* Input boundary assertion: `^`, `$`
* Lookahead assertion: `(?=...)`, `(?!...)`
* Lookbehind assertion: `(?<=...)`, `(?<!...)`
* Character escape: `\n`, `\u{...}`


Wildcard: . - JavaScript

Wildcard: .
===========

A **wildcard** matches all characters except line terminators. It also matches line terminators if the `s` flag is set.

Syntax
------

```regex
.
```

Description
-----------

`.` matches any character except line terminators. If the `s` flag is set, `.` also matches line terminators.

The exact character set matched by `.` depends on whether the regex is Unicode-aware. If it is Unicode-aware, `.` matches any Unicode code point; otherwise, it matches any UTF-16 code unit. For example:

```js
/../.test("😄"); // true; matches two UTF-16 code units as a surrogate pair
/../u.test("😄"); // false; input only has one Unicode character
```

Examples
--------

### Usage with quantifiers

Wildcards are often used with quantifiers to match any character sequence, until the next character of interest is found. For example, the following example extracts the title of a Markdown page in the form `# Title`:

```js
function parseTitle(entry) {
  // Use multiline mode because the title may not be at the start of
  // the file. Note that the m flag does not make . match line
  // terminators, so the title must be on a single line
  // Return text matched by the first capturing group.
  return /^#[ \t]+(.+)$/m.exec(entry)?.[1];
}

parseTitle("# Hello world"); // "Hello world"
parseTitle("## Subsection"); // undefined
parseTitle(`
---
slug: Web/JavaScript/Reference/Regular\_expressions/Wildcard
---

# Wildcard: .

A \*\*wildcard\*\* matches all characters except line terminators.
`); // "Wildcard: ."
```

### Matching code block content

The following example matches the content of a code block enclosed by three backticks in Markdown. It uses the `s` flag to make `.` match line terminators, because the content of a code block may span multiple lines:

```js
function parseCodeBlock(entry) {
  return /^```.\*?^(.+?)\n```/ms.exec(entry)?.[1];
}

parseCodeBlock(`
\`\`\`js
console.log("Hello world");
\`\`\`
`); // "console.log("Hello world");"

parseCodeBlock(`
A \`try...catch\` statement must have the blocks enclosed in curly braces.

\`\`\`js example-bad
try
 doSomething();
catch (e)
 console.log(e);
\`\`\`
`); // "try\n doSomething();\ncatch (e)\n console.log(e);"
```

**Warning:** These examples are for demonstration only. If you want to parse Markdown, use a dedicated Markdown parser because there are many edge cases to consider.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Atom |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Character classes guide
* Regular expressions
* Character class: `[...]`, `[^...]`
* Character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`


Literal character: a, b - JavaScript

Literal character: a, b
=======================

A **literal character** specifies exactly itself to be matched in the input text.

Syntax
------

```regex
c
```

### Parameters

`c`

A single character that is not one of the syntax characters described below.

Description
-----------

In regular expressions, most characters can appear literally. They are usually the most basic building blocks of patterns. For example, here is a pattern from the Removing HTML tags example:

```js
const pattern = /<.+?>/g;
```

In this example, `.`, `+`, and `?` are called *syntax characters*. They have special meanings in regular expressions. The rest of the characters in the pattern (`<` and `>`) are literal characters. They match themselves in the input text: the left and right angle brackets.

The following characters are syntax characters in regular expressions, and they cannot appear as literal characters:

* `^`, `$`
* `\`
* `*`, `+`, `?`, `{`, `}`
* `(`, `)`
* `[`, `]`
* `|`

Within character classes, more characters can appear literally. For more information, see the Character class page. For example `\.` and `[.]` both match a literal `.`. In `v`-mode character classes, however, there are a different set of characters reserved as syntax characters. To be most comprehensive, below is a table of ASCII characters and whether they may appear escaped or unescaped in different contexts, where "✅" means the character represents itself, "❌" means it throws a syntax error, and "⚠" means the character is valid but means something other than itself.

| Characters | Outside character classes in `u` or `v` mode | In `u`-mode character classes | In `v`-mode character classes |
| --- | --- | --- | --- |
| Unescaped | Escaped | Unescaped | Escaped | Unescaped | Escaped |
| `123456789 "'ACEFGHIJKLMNOPQRTUVXYZ_aceghijklmopquxyz` | ✅ | ❌ | ✅ | ❌ | ✅ | ❌ |
| `!#%&,:;<=>@`~` | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ |
| `]` | ❌ | ✅ | ❌ | ✅ | ❌ | ✅ |
| `()[{}` | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ |
| `*+?` | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
| `/` | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ |
| `0DSWbdfnrstvw` | ✅ | ⚠ | ✅ | ⚠ | ✅ | ⚠ |
| `B` | ✅ | ⚠ | ✅ | ❌ | ✅ | ❌ |
| `$.` | ⚠ | ✅ | ✅ | ✅ | ✅ | ✅ |
| `|` | ⚠ | ✅ | ✅ | ✅ | ❌ | ✅ |
| `-` | ✅ | ❌ | ✅⚠ | ✅ | ❌⚠ | ✅ |
| `^` | ⚠ | ✅ | ✅⚠ | ✅ | ✅⚠ | ✅ |
| `\` | ❌⚠ | ✅ | ❌⚠ | ✅ | ❌⚠ | ✅ |

**Note:** The characters that can both be escaped and unescaped in `v`-mode character classes are exactly those forbidden as "double punctuators". See `v`-mode character classes for more information.

Whenever you want to match a syntax character literally, you need to escape it with a backslash (`\`). For example, to match a literal `*` in a pattern, you need to write `\*` in the pattern. Using syntax characters as literal characters either leads to unexpected results or causes syntax errors — for example, `/*/` is not a valid regular expression because the quantifier is not preceded by a pattern. In Unicode-unaware mode, `]`, `{`, and `}` may appear literally if it's not possible to parse them as the end of a character class or quantifier delimiters. This is a deprecated syntax for web compatibility, and you should not rely on it.

Regular expression literals cannot be specified with certain non-syntax literal characters. `/` cannot appear as a literal character in a regular expression literal, because `/` is used as the delimiter of the literal itself. You need to escape it as `\/` if you want to match a literal `/`. Line terminators cannot appear as literal characters in a regular expression literal either, because a literal cannot span multiple lines. You need to use a character escape like `\n` instead. There are no such restrictions when using the `RegExp()` constructor, although string literals have their own escaping rules (for example, `"\\"` actually denotes a single backslash character, so `new RegExp("\\*")` and `/\*/` are equivalent).

In Unicode-unaware mode, the pattern is interpreted as a sequence of UTF-16 code units. This means surrogate pairs actually represent two literal characters. This causes unexpected behaviors when paired with other features:

```js
/^[😄]$/.test("😄"); // false, because the pattern is interpreted as /^[\ud83d\udc04]$/
/^😄+$/.test("😄😄"); // false, because the pattern is interpreted as /^\ud83d\udc04+$/
```

In Unicode-aware mode, the pattern is interpreted as a sequence of Unicode code points, and surrogate pairs do not get split. Therefore, you should always prefer to use the `u` flag.

Examples
--------

### Using literal characters

The following example is copied from Character escape. The `a` and `b` characters are literal characters in the pattern, and `\n` is an escaped character because it cannot appear literally in a regular expression literal.

```js
const pattern = /a\nb/;
const string = `a
b`;
console.log(pattern.test(string)); // true
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-PatternCharacter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Character classes guide
* Regular expressions
* Character escape: `\n`, `\u{...}`


Character class: [...], [^...] - JavaScript

Character class: [...], [^...]
==============================

A **character class** matches any character in or not in a custom set of characters. When the `v` flag is enabled, it can also be used to match finite-length strings.

Syntax
------

```regex
[]
[abc]
[A-Z]

[^]
[^abc]
[^A-Z]

// `v` mode only
[operand1&&operand2]
[operand1--operand2]
[\q{substring}]
```

### Parameters

`operand1`, `operand2`

Can be a single character, another square-bracket-enclosed character class, a character class escape, a Unicode character class escape, or a string using the `\q` syntax.

`substring`

A literal string.

Description
-----------

A character class specifies a list of characters between square brackets and matches any character in the list. The `v` flag drastically changes how character classes are parsed and interpreted. The following syntaxes are available in both `v` mode and non-`v` mode:

* A single character: matches the character itself.
* A range of characters: matches any character in the inclusive range. The range is specified by two characters separated by a dash (`-`). The first character must be smaller in character value than the second character. The *character value* is the Unicode code point of the character. Because Unicode code points are usually assigned to alphabets in order, `[a-z]` specifies all lowercase Latin characters, while `[α-ω]` specifies all lowercase Greek characters. In Unicode-unaware mode, regexes are interpreted as a sequence of BMP characters. Therefore, surrogate pairs in character classes represent two characters instead of one; see below for details.
* Escape sequences: `\b`, `\-`, character class escapes, Unicode character class escapes, and other character escapes.

These syntaxes can occur any number of times, and the character sets they represent are unioned. For example, `/[a-zA-Z0-9]/` matches any letter or digit.

The `^` prefix in a character class creates a *complement class*. For example, `[^abc]` matches any character except `a`, `b`, or `c`. The `^` character is a literal character when it appears in the middle of a character class — for example, `[a^b]` matches the characters `a`, `^`, and `b`.

The lexical grammar does a very rough parse of regex literals, so that it does not end the regex literal at a `/` character which appears within a character class. This means `/[/]/` is valid without needing to escape the `/`.

The boundaries of a character range must not specify more than one character, which happens if you use a character class escape. For example:

```js
/[\s-9]/u; // SyntaxError: Invalid regular expression: Invalid character class
```

In Unicode-unaware mode, character ranges where one boundary is a character class makes the `-` become a literal character. This is a deprecated syntax for web compatibility, and you should not rely on it.

```js
/[\s-9]/.test("-"); // true
```

In Unicode-unaware mode, regexes are interpreted as a sequence of BMP characters. Therefore, surrogate pairs in character classes represent two characters instead of one.

```js
/[😄]/.test("\ud83d"); // true
/[😄]/u.test("\ud83d"); // false

/[😄-😛]/.test("😑"); // SyntaxError: Invalid regular expression: /[😄-😛]/: Range out of order in character class
/[😄-😛]/u.test("😑"); // true
```

Even if the pattern ignores case, the case of the two ends of a range is significant in determining which characters belong to the range. For example, the pattern `/[E-F]/i` only matches `E`, `F`, `e`, and `f`, while the pattern `/[E-f]/i` matches all uppercase and lowercase ASCII letters (because it spans over `E–Z` and `a–f`), as well as `[`, `\`, `]`, `^`, `_`, and ```.

### Non-v-mode character class

Non-`v`-mode character classes interpret most character literally and have less restrictions about the characters they can contain. For example, `.` is the literal dot character, not the wildcard. The only characters that cannot appear literally are `\`, `]`, and `-`.

* In character classes, most escape sequences are supported, except `\b`, `\B`, and backreferences. `\b` indicates a backspace character instead of a word boundary, while the other two cause syntax errors. To use `\` literally, escape it as `\\`.
* The `]` character indicates the end of the character class. To use it literally, escape it as `\]`.
* The dash (`-`) character, when used between two characters, indicates a range. When it appears at the start or end of a character class, it is a literal character. It's also a literal character when it's used in the boundary of a range. For example, `[a-]` matches the characters `a` and `-`, `[!--]` matches the characters `!` to `-`, and `[--9]` matches the characters `-` to `9`. You can also escape it as `\-` if you want to use it literally anywhere.
### v-mode character class

The basic idea of character classes in `v` mode remains the same: you can still use most characters literally, use `-` to denote character ranges, and use escape sequences. One of the most important features of the `v` flag is *set notation* within character classes. As previously mentioned, normal character classes can express unions by concatenating two ranges, such as using `[A-Z0-9]` to mean "the union of the set `[A-Z]` and the set `[0-9]`". However, there's no easy way to represent other operations with character sets, such as intersection and difference.

With the `v` flag, intersection is expressed with `&&`, and subtraction with `--`. The absence of both implies union. The two operands of `&&` or `--` can be a character, character escape, character class escape, or even another character class. For example, to express "a word character that's not an underscore", you can use `[\w--_]`. You cannot mix operators on the same level. For example, `[\w&&[A-z]--_]` is a syntax error. However, because you can nest character classes, you can be explicit by writing `[\w&&[[A-z]--_]]` or `[[\w&&[A-z]]--_]` (which both mean `[A-Za-z]`). Similarly, `[AB--C]` is invalid and you need to write `[A[B--C]]` (which just means `[AB]`).

In `v` mode, the Unicode character class escape `\p` can match finite-length strings, such as emojis. For symmetry, regular character classes can also match more than one character. To write a "string literal" in a character class, you wrap the string in `\q{...}`. The only regex syntax supported here is disjunction — apart from this, `\q` must completely enclose literals (including escaped characters). This ensures that character classes can only match finite-length strings with finitely many possibilities.

Because the character class syntax is now more sophisticated, more characters are reserved and forbidden from appearing literally.

* In addition to `]` and `\`, the following characters must be escaped in character classes if they represent literal characters: `(`, `)`, `[`, `{`, `}`, `/`, `-`, `|`. This list is somewhat similar to the list of syntax characters, except that `^`, `$`, `*`, `+`, and `?` are not reserved inside character classes, while `/` and `-` are not reserved outside character classes (although `/` may delimit a regex literal and therefore still needs to be escaped). All these characters may also be optionally escaped in `u`-mode character classes.
* The following "double punctuator" sequences must be escaped as well (but they don't make much sense without the `v` flag anyway): `&&`, `!!`, `##`, `$$`, `%%`, `**`, `++`, `,,`, `..`, `::`, `;;`, `<<`, `==`, `>>`, `??`, `@@`, `^^`, ````, `~~`. In `u` mode, some of these characters can only appear literally within character classes and cause a syntax error when escaped. In `v` mode, they must be escaped when appearing in pairs, but can be optionally escaped when appearing alone. For example, `/[\!]/u` is invalid because it's an identity escape, but both `/[\!]/v` and `/[!]/v` are valid, while `/[!!]/v` is invalid. The literal character reference has a detailed table of which characters can appear escaped or unescaped.

Complement character classes `[^...]` cannot possibly be able to match strings longer than one character. For example, `[\q{ab|c}]` is valid and matches the string `"ab"`, but `[^\q{ab|c}]` is invalid because it's unclear how many characters should be consumed. The check is done by checking if all `\q` contain single characters and all `\p` specify character properties — for unions, all operands must be purely characters; for intersections, at least one operand must be purely characters; for subtraction, the leftmost operand must be purely characters. The check is syntactic without looking at the actual character set being specified, which means although `/[^\q{ab|c}--\q{ab}]/v` is equivalent to `/[^c]/v`, it's still rejected.

### Complement classes and case-insensitive matching

In non-`v`-mode, complement character classes `[^...]` are implemented by simply inverting the match result — that is, `[^...]` matches whenever `[...]` doesn't match, and vice versa. However, the other complement classes, such as `\P{...}` and `\W`, work by eagerly constructing the set consisting of all characters without the specified property. They seem to produce the same behavior, but are made more complex when combined with case-insensitive matching.

Consider the following two regexes:

```js
const r1 = /\p{Lowercase\_Letter}/iu;
const r2 = /[^\P{Lowercase\_Letter}]/iu;
```

The `r2` is a double negation and seems to be equivalent with `r1`. But in fact, `r1` matches all lower- and upper-case ASCII letters, while `r2` matches none. To illustrate how it works, pretend that we are only dealing with ASCII characters, not the entire Unicode character set, and `r1` and `r2` are specified as below:

```js
const r1 = /[a-z]/iu;
const r2 = /[^A-Z]/iu;
```

Recall that case-insensitive matching happens by folding both the pattern and the input to the same case (see `ignoreCase` for more details). For `r1`, the character class `a-z` stays the same after case folding, while both upper- and lower-case ASCII string inputs are folded to lower-case, so `r1` is able to match both `"A"` and `"a"`. For `r2`, the character class `A-Z` is folded to `a-z`; however, `^` negates the match result, so that `[^A-Z]` in effect only matches upper-case strings. However, both upper- and lower-case ASCII string inputs are still folded to lower-case, causing `r2` to match nothing.

In `v` mode, this behavior is fixed — `[^...]` also eagerly constructs the complement class instead of negating the match result. This makes `[^\P{Lowercase_Letter}]` and `\p{Lowercase_Letter}` are strictly equivalent.

Examples
--------

### Matching hexadecimal digits

The following function determines whether a string contains a valid hexadecimal number:

```js
function isHexadecimal(str) {
  return /^[0-9A-F]+$/i.test(str);
}

isHexadecimal("2F3"); // true
isHexadecimal("beef"); // true
isHexadecimal("undefined"); // false
```

### Using intersection

The following function matches Greek letters.

```js
function greekLetters(str) {
  return str.match(/[\p{Script\_Extensions=Greek}&&\p{Letter}]/gv);
}

// 𐆊 is U+1018A GREEK ZERO SIGN
greekLetters("π𐆊P0零αAΣ"); // [ 'π', 'α', 'Σ' ]
```

### Using subtraction

The following function matches all non-ASCII numbers.

```js
function nonASCIINumbers(str) {
  return str.match(/[\p{Decimal\_Number}--[0-9]]/gv);
}

// 𑜹 is U+11739 AHOM DIGIT NINE
nonASCIINumbers("𐆊0零1𝟜𑜹a"); // [ '𝟜', '𑜹' ]
```

### Matching strings

The following function matches all line terminator sequences, including the line terminator characters and the sequence `\r\n` (CRLF).

```js
function getLineTerminators(str) {
  return str.match(/[\r\n\u2028\u2029\q{\r\n}]/gv);
}

getLineTerminators(`
A poem\r
Is split\r\n
Into many
Stanzas
`); // [ '\r', '\r\n', '\n' ]
```

This example is exactly equivalent to `/(?:\r|\n|\u2028|\u2029|\r\n)/gu` or `/(?:[\r\n\u2028\u2029]|\r\n)/gu`, except shorter.

The most useful case of `\q{}` is when doing subtraction and intersection. Previously, this was possible with multiple lookaheads. The following function matches flags that are not one of the American, Chinese, Russian, British, and French flags.

```js
function notUNSCPermanentMember(flag) {
  return /^[\p{RGI\_Emoji\_Flag\_Sequence}--\q{🇺🇸|🇨🇳|🇷🇺|🇬🇧|🇫🇷}]$/v.test(flag);
}

notUNSCPermanentMember("🇺🇸"); // false
notUNSCPermanentMember("🇩🇪"); // true
```

This example is mostly equivalent to `/^(?!🇺🇸|🇨🇳|🇷🇺|🇬🇧|🇫🇷)\p{RGI_Emoji_Flag_Sequence}$/v`, except perhaps more performant.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-CharacterClass |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Character classes guide
* Regular expressions
* Character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`
* Unicode character class escape: `\p{...}`, `\P{...}`
* Literal character: `a`, `b`
* Character escape: `\n`, `\u{...}`
* Disjunction: `|`
* RegExp v flag with set notation and properties of strings on v8.dev (2022)


Input boundary assertion: ^, $ - JavaScript

Input boundary assertion: ^, $
==============================

An **input boundary assertion** checks if the current position in the string is an input boundary. An input boundary is the start or end of the string; or, if the `m` flag is set, the start or end of a line.

Syntax
------

```regex
^
$
```

Description
-----------

`^` asserts that the current position is the start of input. `$` asserts that the current position is the end of input. Both are *assertions*, so they don't consume any characters.

More precisely, `^` asserts that the character to the left is out of bounds of the string; `$` asserts that the character to the right is out of bounds of the string. If the `m` flag is set, `^` also matches if the character to the left is a line terminator character, and `$` also matches if the character to the right is a line terminator.

Unless the `m` flag is set, the `^` and `$` assertions only make sense when placed at the boundaries of the pattern, because any other characters to the left or right of them would necessarily cause the assertion to fail.

The `y` flag doesn't change the meaning of these assertions — see also anchored sticky flag.

Examples
--------

### Removing trailing slashes

The following example removes trailing slashes from a URL string:

```js
function removeTrailingSlash(url) {
  return url.replace(/\/$/, "");
}

removeTrailingSlash("https://example.com/"); // "https://example.com"
removeTrailingSlash("https://example.com/docs/"); // "https://example.com/docs"
```

### Matching file extensions

The following example checks file types by matching the file extension, which always comes at the end of the string:

```js
function isImage(filename) {
  return /\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);
}

isImage("image.png"); // true
isImage("image.jpg"); // true
isImage("image.pdf"); // false
```

### Matching entire input

Sometimes you want to make sure that your regex matches the entire input, not just a substring of the input. For example, if you are determining if a string is a valid identifier, you can add input boundary assertions to both ends of the pattern:

```js
function isValidIdentifier(str) {
  return /^[$\_\p{ID\_Start}][$\_\p{ID\_Continue}]\*$/u.test(str);
}

isValidIdentifier("foo"); // true
isValidIdentifier("$1"); // true
isValidIdentifier("1foo"); // false
isValidIdentifier(" foo "); // false
```

This function is useful when doing codegen (generating code using code), because you can use valid identifiers differently from other string properties, such as dot notation instead of bracket notation:

```js
const variables = ["foo", "foo:bar", " foo "];

function toAssignment(key) {
  if (isValidIdentifier(key)) {
    return `globalThis.${key} = undefined;`;
  }
  // JSON.stringify() escapes quotes and other special characters
  return `globalThis[${JSON.stringify(key)}] = undefined;`;
}

const statements = variables.map(toAssignment).join("\n");

console.log(statements);
// globalThis.foo = undefined;
// globalThis["foo:bar"] = undefined;
// globalThis[" foo "] = undefined;
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Assertion |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Assertions guide
* Regular expressions
* Word boundary assertion: `\b`, `\B`
* Lookahead assertion: `(?=...)`, `(?!...)`
* Lookbehind assertion: `(?<=...)`, `(?<!...)`


Named backreference: \k<name> - JavaScript

Named backreference: \k<name>
=============================

A **named backreference** refers to the submatch of a previous named capturing group and matches the same text as that group. For unnamed capturing groups, you need to use the normal backreference syntax.

Syntax
------

```regex
\k<name>
```

### Parameters

`name`

The name of the group. Must be a valid identifier and refer to an existent named capturing group.

Description
-----------

Named backreferences are very similar to normal backreferences: it refers to the text matched by a capturing group and matches the same text. The difference is that you refer to the capturing group by name instead of by number. This makes the regular expression more readable and easier to refactor and maintain.

In Unicode-unaware mode, the sequence `\k` only starts a named backreference if the regex contains at least one named capturing group. Otherwise, it is an identity escape and is the same as the literal character `k`. This is a deprecated syntax for web compatibility, and you should not rely on it.

```js
/\k/.test("k"); // true
```

Examples
--------

### Pairing quotes

The following function matches the `title='xxx'` and `title="xxx"` patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group (`[2]`) returns the string between the matching quote characters:

```js
function parseTitle(metastring) {
  return metastring.match(/title=(?<quote>["'])(.\*?)\k<quote>/)[2];
}

parseTitle('title="foo"'); // 'foo'
parseTitle("title='foo' lang='en'"); // 'foo'
parseTitle('title="Named capturing groups\' advantages"'); // "Named capturing groups' advantages"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-AtomEscape |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Groups and backreferences guide
* Regular expressions
* Capturing group: `(...)`
* Named capturing group: `(?<name>...)`
* Backreference: `\1`, `\2`


Character escape: \n, \u{...} - JavaScript

Character escape: \n, \u{...}
=============================

A **character escape** represents a character that may not be able to be conveniently represented in its literal form.

Syntax
------

```regex
\f, \n, \r, \t, \v
\cA, \cB, …, \cz
\0
\^, \$, \\, \., \\*, \+, \?, \(, \), \[, \], {, }, \|, \/

\xHH
\uHHHH
\u{HHH}
```

**Note:** `,` is not part of the syntax.

### Parameters

`HHH`

A hexadecimal number representing the Unicode code point of the character. The `\xHH` form must have two hexadecimal digits; the `\uHHHH` form must have four; the `\u{HHH}` form may have 1 to 6 hexadecimal digits.

Description
-----------

The following character escapes are recognized in regular expressions:

`\f`, `\n`, `\r`, `\t`, `\v`

Same as those in string literals, except `\b`, which represents a word boundary in regexes unless in a character class.

`\c` followed by a letter from `A` to `Z` or `a` to `z`

Represents the control character with value equal to the letter's character value modulo 32. For example, `\cJ` represents line break (`\n`), because the code point of `J` is 74, and 74 modulo 32 is 10, which is the code point of line break. Because an uppercase letter and its lowercase form differ by 32, `\cJ` and `\cj` are equivalent. You can represent control characters from 1 to 26 in this form.

`\0`

Represents the U+0000 NUL character. Cannot be followed by a digit (which makes it a legacy octal escape sequence).

`\^`, `\$`, `\\`, `\.` `\*`, `\+`, `\?`, `\(`, `\)`, `\[`, `\]`, `{`, `}`, `\|`, `\/`

Represents the character itself. For example, `\\` represents a backslash, and `\(` represents a left parenthesis. These are syntax characters in regexes (`/` is the delimiter of a regex literal), so they require escaping unless in a character class.

`\xHH`

Represents the character with the given hexadecimal Unicode code point. The hexadecimal number must be exactly two digits long.

`\uHHHH`

Represents the character with the given hexadecimal Unicode code point. The hexadecimal number must be exactly four digits long. Two such escape sequences can be used to represent a surrogate pair in Unicode-aware mode. (In Unicode-unaware mode, they are always two separate characters.)

`\u{HHH}`

(Unicode-aware mode only) Represents the character with the given hexadecimal Unicode code point. The hexadecimal number can be from 1 to 6 digits long.

In Unicode-unaware mode, escape sequences that are not one of the above become *identity escapes*: they represent the character that follows the backslash. For example, `\a` represents the character `a`. This behavior limits the ability to introduce new escape sequences without causing backward compatibility issues, and is therefore forbidden in Unicode-aware mode.

In Unicode-unaware mode, `]`, `{`, and `}` may appear literally if it's not possible to parse them as the end of a character class or quantifier delimiters. This is a deprecated syntax for web compatibility, and you should not rely on it.

In Unicode-unaware mode, escape sequences within character classes of the form `\cX` where `X` is a number or `_` are decoded in the same way as those with ASCII letters: `\c0` is the same as `\cP` when taken modulo 32. In addition, if the form `\cX` is encountered anywhere where `X` is not one of the recognized characters, then the backslash is treated as a literal character. These syntaxes are also deprecated.

```js
/[\c0]/.test("\x10"); // true
/[\c_]/.test("\x1f"); // true
/[\c\*]/.test("\\"); // true
/\c/.test("\\c"); // true
/\c0/.test("\\c0"); // true (the \c0 syntax is only supported in character classes)
```

Examples
--------

### Using character escapes

Character escapes are useful when you want to match a character that is not easily represented in its literal form. For example, you cannot use a line break literally in a regex literal, so you must use a character escape:

```js
const pattern = /a\nb/;
const string = `a
b`;
console.log(pattern.test(string)); // true
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-CharacterEscape |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Character classes guide
* Regular expressions
* Character class: `[...]`, `[^...]`
* Character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`
* Literal character: `a`, `b`
* Unicode character class escape: `\p{...}`, `\P{...}`
* Backreference: `\1`, `\2`
* Named backreference: `\k<name>`
* Word boundary assertion: `\b`, `\B`


Capturing group: (...) - JavaScript

Capturing group: (...)
======================

A **capturing group** groups a subpattern, allowing you to apply a quantifier to the entire group or use disjunctions within it. It memorizes information about the subpattern match, so that you can refer back to it later with a backreference, or access the information through the match results.

If you don't need the result of the subpattern match, use a non-capturing group instead, which improves performance and avoids refactoring hazards.

Syntax
------

```regex
(pattern)
```

### Parameters

`pattern`

A pattern consisting of anything you may use in a regex literal, including a disjunction.

Description
-----------

A capturing group acts like the grouping operator in JavaScript expressions, allowing you to use a subpattern as a single atom.

Capturing groups are numbered by the order of their opening parentheses. The first capturing group is numbered `1`, the second `2`, and so on. Named capturing groups are also capturing groups and are numbered together with other (unnamed) capturing groups. The information of the capturing group's match can be accessed through:

* The return value (which is an array) of `RegExp.prototype.exec()`, `String.prototype.match()`, and `String.prototype.matchAll()`
* The `pN` parameters of the `String.prototype.replace()` and `String.prototype.replaceAll()` methods' `replacement` callback function
* Backreferences within the same pattern

**Note:** Even in `exec()`'s result array, capturing groups are accessed by numbers `1`, `2`, etc., because the `0` element is the entire match. `\0` is not a backreference, but a character escape for the NUL character.

Capturing groups in the regex source code correspond to their results one-to-one. If a capturing group is not matched (for example, it belongs to an unmatched alternative in a disjunction), the corresponding result is `undefined`.

```js
/(ab)|(cd)/.exec("cd"); // ['cd', undefined, 'cd']
```

Capturing groups can be quantified. In this case, the match information corresponding to this group is the last match of the group.

```js
/([ab])+/.exec("abc"); // ['ab', 'b']; because "b" comes after "a", this result overwrites the previous one
```

Capturing groups can be used in lookahead and lookbehind assertions. Because lookbehind assertions match their atoms backwards, the final match corresponding to this group is the one that appears to the *left* end of the string. However, the indices of the match groups still correspond to their relative locations in the regex source.

```js
/c(?=(ab))/.exec("cab"); // ['c', 'ab']
/(?<=(a)(b))c/.exec("abc"); // ['c', 'a', 'b']
/(?<=([ab])+)c/.exec("abc"); // ['c', 'a']; because "a" is seen by the lookbehind after the lookbehind has seen "b"
```

Capturing groups can be nested, in which case the outer group is numbered first, then the inner group, because they are ordered by their opening parentheses. If a nested group is repeated by a quantifier, then each time the group matches, the subgroups' results are all overwritten, sometimes with `undefined`.

```js
/((a+)?(b+)?(c))\*/.exec("aacbbbcac"); // ['aacbbbcac', 'ac', 'a', undefined, 'c']
```

In the example above, the outer group is matched three times:

1. Matches `"aac"`, with subgroups `"aa"`, `undefined`, and `"c"`.
2. Matches `"bbbc"`, with subgroups `undefined`, `"bbb"`, and `"c"`.
3. Matches `"ac"`, with subgroups `"a"`, `undefined`, and `"c"`.

The `"bbb"` result from the second match is not preserved, because the third match overwrites it with `undefined`.

You can get the start and end indices of each capturing group in the input string by using the `d` flag. This creates an extra `indices` property on the array returned by `exec()`.

You can optionally specify a name to a capturing group, which helps avoid pitfalls related to group positions and indexing. See Named capturing groups for more information.

Parentheses have other purposes in different regex syntaxes. For example, they also enclose lookahead and lookbehind assertions. Because these syntaxes all start with `?`, and `?` is a quantifier which normally cannot occur directly after `(`, this does not lead to ambiguities.

Examples
--------

### Matching date

The following example matches a date in the format `YYYY-MM-DD`:

```js
function parseDate(input) {
  const parts = /^(\d{4})-(\d{2})-(\d{2})$/.exec(input);
  if (!parts) {
    return null;
  }
  return parts.slice(1).map((p) => parseInt(p, 10));
}

parseDate("2019-01-01"); // [2019, 1, 1]
parseDate("2019-06-19"); // [2019, 6, 19]
```

### Pairing quotes

The following function matches the `title='xxx'` and `title="xxx"` patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group (`[2]`) returns the string between the matching quote characters:

```js
function parseTitle(metastring) {
  return metastring.match(/title=(["'])(.\*?)\1/)[2];
}

parseTitle('title="foo"'); // 'foo'
parseTitle("title='foo' lang='en'"); // 'foo'
parseTitle('title="Named capturing groups\' advantages"'); // "Named capturing groups' advantages"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Atom |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Groups and backreferences guide
* Regular expressions
* Non-capturing group: `(?:...)`
* Named capturing group: `(?<name>...)`
* Backreference: `\1`, `\2`


Quantifier: *, +, ?, {n}, {n,}, {n,m} - JavaScript

Quantifier: \*, +, ?, {n}, {n,}, {n,m}
======================================

A **quantifier** repeats an atom a certain number of times. The quantifier is placed after the atom it applies to.

Syntax
------

```regex
// Greedy
atom?
atom\*
atom+
atom{count}
atom{min,}
atom{min,max}

// Non-greedy
atom??
atom\*?
atom+?
atom{count}?
atom{min,}?
atom{min,max}?
```

### Parameters

`atom`

A single atom.

`count`

A non-negative integer. The number of times the atom should be repeated.

`min`

A non-negative integer. The minimum number of times the atom can be repeated.

`max` Optional

A non-negative integer. The maximum number of times the atom can be repeated. If omitted, the atom can be repeated as many times as needed.

Description
-----------

A quantifier is placed after an atom to repeat it a certain number of times. It cannot appear on its own. Each quantifier is able to specify a minimum and maximum number that a pattern must be repeated for.

| Quantifier | Minimum | Maximum |
| --- | --- | --- |
| `?` | 0 | 1 |
| `*` | 0 | Infinity |
| `+` | 1 | Infinity |
| `{count}` | `count` | `count` |
| `{min,}` | `min` | Infinity |
| `{min,max}` | `min` | `max` |

For the `{count}`, `{min,}`, and `{min,max}` syntaxes, there cannot be white spaces around the numbers — otherwise, it becomes a literal pattern.

```js
const re = /a{1, 3}/;
re.test("aa"); // false
re.test("a{1, 3}"); // true
```

This behavior is fixed in Unicode-aware mode, where braces cannot appear literally without escaping. The ability to use `{` and `}` literally without escaping is a deprecated syntax for web compatibility, and you should not rely on it.

```js
/a{1, 3}/u; // SyntaxError: Invalid regular expression: Incomplete quantifier
```

It is a syntax error if the minimum is greater than the maximum.

```js
/a{3,2}/; // SyntaxError: Invalid regular expression: numbers out of order in {} quantifier
```

Quantifiers can cause capturing groups to match multiple times. See the capturing groups page for more information on the behavior in this case.

Each repeated match doesn't have to be the same string.

```js
/[ab]\*/.exec("aba"); // ['aba']
```

Quantifiers are *greedy* by default, which means they try to match as many times as possible until the maximum is reached, or until it's not possible to match further. You can make a quantifier *non-greedy* by adding a `?` after it. In this case, the quantifier will try to match as few times as possible, only matching more times if it's impossible to match the rest of the pattern with this many repetitions.

```js
/a\*/.exec("aaa"); // ['aaa']; the entire input is consumed
/a\*?/.exec("aaa"); // ['']; it's possible to consume no characters and still match successfully
/^a\*?$/.exec("aaa"); // ['aaa']; it's not possible to consume fewer characters and still match successfully
```

However, as soon as the regex successfully matches the string at some index, it will not try subsequent indices, although that may result in fewer characters being consumed.

```js
/a\*?$/.exec("aaa"); // ['aaa']; the match already succeeds at the first character, so the regex never attempts to start matching at the second character
```

Greedy quantifiers may try fewer repetitions if it's otherwise impossible to match the rest of the pattern.

```js
/[ab]+[abc]c/.exec("abbc"); // ['abbc']
```

In this example, `[ab]+` first greedily matches `"abb"`, but `[abc]c` is not able to match the rest of the pattern (`"c"`), so the quantifier is reduced to match only `"ab"`.

Greedy quantifiers avoid matching infinitely many empty strings. If the minimum number of matches is reached and no more characters are being consumed by the atom at this position, the quantifier stops matching. This is why `/(a*)*/.exec("b")` does not result in an infinite loop.

Greedy quantifiers try to match as many *times* as possible; it does not maximize the *length* of the match. For example, `/(aa|aabaac|ba)*/.exec("aabaac")` matches `"aa"` and then `"ba"` instead of `"aabaac"`.

Quantifiers apply to a single atom. If you want to quantify a longer pattern or a disjunction, you must group it. Quantifiers cannot be applied to assertions.

```js
/^\*/; // SyntaxError: Invalid regular expression: nothing to repeat
```

In Unicode-aware mode, lookahead assertions can be quantified. This is a deprecated syntax for web compatibility, and you should not rely on it.

```js
/(?=a)?b/.test("b"); // true; the lookahead is matched 0 time
```

Examples
--------

### Removing HTML tags

The following example removes HTML tags enclosed in angle brackets. Note the use of `?` to avoid consuming too many characters at once.

```js
function stripTags(str) {
  return str.replace(/<.+?>/g, "");
}

stripTags("<p><em>lorem</em> <strong>ipsum</strong></p>"); // 'lorem ipsum'
```

The same effect can be achieved with a greedy match, but not allowing the repeated pattern to match `>`.

```js
function stripTags(str) {
  return str.replace(/<[^>]+>/g, "");
}

stripTags("<p><em>lorem</em> <strong>ipsum</strong></p>"); // 'lorem ipsum'
```

**Warning:** This is for demonstration only — it doesn't handle `>` in attribute values. Use a proper HTML sanitizer like the HTML sanitizer API instead.

### Locating Markdown paragraphs

In Markdown, paragraphs are separated by one or more blank lines. The following example counts all paragraphs in a string by matching two or more line breaks.

```js
function countParagraphs(str) {
  return str.match(/(?:\r?\n){2,}/g).length + 1;
}

countParagraphs(`
Paragraph 1

Paragraph 2
Containing some line breaks, but still the same paragraph

Another paragraph
`); // 3
```

**Warning:** This is for demonstration only — it doesn't handle line breaks in code blocks or other Markdown block elements like headings. Use a proper Markdown parser instead.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Quantifier |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Quantifiers guide
* Regular expressions
* Disjunction: `|`
* Character class: `[...]`, `[^...]`


Unicode character class escape: \p{...}, \P{...} - JavaScript

Unicode character class escape: \p{...}, \P{...}
================================================

A **unicode character class escape** is a kind of character class escape that matches a set of characters specified by a Unicode property. It's only supported in Unicode-aware mode. When the `v` flag is enabled, it can also be used to match finite-length strings.

Try it
------

Syntax
------

```regex
\p{loneProperty}
\P{loneProperty}

\p{property=value}
\P{property=value}
```

### Parameters

`loneProperty`

A lone Unicode property name or value, following the same syntax as `value`. It specifies the value for the `General_Category` property, or a binary property name. In `v` mode, it can also be a binary Unicode property of strings.

**Note:** ICU syntax allows omitting the `Script` property name as well, but JavaScript does not support this, because most of the time `Script_Extensions` is more useful than `Script`.

`property`

A Unicode property name. Must be made of ASCII letters (`A–Z`, `a–z`) and underscores (`_`), and must be one of the non-binary property names.

`value`

A Unicode property value. Must be made of ASCII letters (`A–Z`, `a–z`), underscores (`_`), and digits (`0–9`), and must be one of the supported values listed in `PropertyValueAliases.txt`.

Description
-----------

`\p` and `\P` are only supported in Unicode-aware mode. In Unicode-unaware mode, they are identity escapes for the `p` or `P` character.

Every Unicode character has a set of properties that describe it. For example, the character `a` has the `General_Category` property with value `Lowercase_Letter`, and the `Script` property with value `Latn`. The `\p` and `\P` escape sequences allow you to match a character based on its properties. For example, `a` can be matched by `\p{Lowercase_Letter}` (the `General_Category` property name is optional) as well as `\p{Script=Latn}`. `\P` creates a *complement class* that consists of code points without the specified property.

To compose multiple properties, use the character set intersection syntax enabled with the `v` flag, or see pattern subtraction and intersection.

In `v` mode, `\p` may match a sequence of code points, defined in Unicode as "properties of strings". This is most useful for emojis, which are often composed of multiple code points. However, `\P` can only complement character properties.

**Note:** There are plans to port the properties of strings feature to `u` mode as well.

Examples
--------

### General categories

General categories are used to classify Unicode characters and subcategories are available to define a more precise categorization. It is possible to use both short or long forms in Unicode property escapes.

They can be used to match letters, numbers, symbols, punctuations, spaces, etc. For a more exhaustive list of general categories, please refer to the Unicode specification.

```js
// finding all the letters of a text
const story = "It's the Cheshire Cat: now I shall have somebody to talk to.";

// Most explicit form
story.match(/\p{General\_Category=Letter}/gu);

// It is not mandatory to use the property name for General categories
story.match(/\p{Letter}/gu);

// This is equivalent (short alias):
story.match(/\p{L}/gu);

// This is also equivalent (conjunction of all the subcategories using short aliases)
story.match(/\p{Lu}|\p{Ll}|\p{Lt}|\p{Lm}|\p{Lo}/gu);
```

### Scripts and script extensions

Some languages use different scripts for their writing system. For instance, English and Spanish are written using the Latin script while Arabic and Russian are written with other scripts (respectively Arabic and Cyrillic). The `Script` and `Script_Extensions` Unicode properties allow regular expression to match characters according to the script they are mainly used with (`Script`) or according to the set of scripts they belong to (`Script_Extensions`).

For example, `A` belongs to the `Latin` script and `ε` to the `Greek` script.

```js
const mixedCharacters = "aεЛ";

// Using the canonical "long" name of the script
mixedCharacters.match(/\p{Script=Latin}/u); // a

// Using a short alias (ISO 15924 code) for the script
mixedCharacters.match(/\p{Script=Grek}/u); // ε

// Using the short name sc for the Script property
mixedCharacters.match(/\p{sc=Cyrillic}/u); // Л
```

For more details, refer to the Unicode specification, the Scripts table in the ECMAScript specification, and the ISO 15924 list of script codes.

If a character is used in a limited set of scripts, the `Script` property will only match for the "predominant" used script. If we want to match characters based on a "non-predominant" script, we could use the `Script_Extensions` property (`Scx` for short).

```js
// ٢ is the digit 2 in Arabic-Indic notation
// while it is predominantly written within the Arabic script
// it can also be written in the Thaana script

"٢".match(/\p{Script=Thaana}/u);
// null as Thaana is not the predominant script

"٢".match(/\p{Script\_Extensions=Thaana}/u);
// ["٢", index: 0, input: "٢", groups: undefined]
```

### Unicode property escapes vs. character classes

With JavaScript regular expressions, it is also possible to use character classes and especially `\w` or `\d` to match letters or digits. However, such forms only match characters from the *Latin* script (in other words, `a` to `z` and `A` to `Z` for `\w` and `0` to `9` for `\d`). As shown in this example, it might be a bit clumsy to work with non Latin texts.

Unicode property escapes categories encompass much more characters and `\p{Letter}` or `\p{Number}` will work for any script.

```js
// Trying to use ranges to avoid \w limitations:

const nonEnglishText = "Приключения Алисы в Стране чудес";
const regexpBMPWord = /([\u0000-\u0019\u0021-\uFFFF])+/gu;
// BMP goes through U+0000 to U+FFFF but space is U+0020

console.table(nonEnglishText.match(regexpBMPWord));

// Using Unicode property escapes instead
const regexpUPE = /\p{L}+/gu;
console.table(nonEnglishText.match(regexpUPE));
```

### Matching prices

The following example matches prices in a string:

```js
function getPrices(str) {
  // Sc stands for "currency symbol"
  return [...str.matchAll(/\p{Sc}\s\*[\d.,]+/gu)].map((match) => match[0]);
}

const str = `California rolls $6.99
Crunchy rolls $8.49
Shrimp tempura $10.99`;
console.log(getPrices(str)); // ["$6.99", "$8.49", "$10.99"]

const str2 = `US store $19.99
Europe store €18.99
Japan store ¥2000`;
console.log(getPrices(str2)); // ["$19.99", "€18.99", "¥2000"]
```

### Matching strings

With the `v` flag, `\p{…}` can match strings that are potentially longer than one character by using a property of strings:

```js
const flag = "🇺🇳";
console.log(flag.length); // 2
console.log(/\p{RGI\_Emoji\_Flag\_Sequence}/v.exec(flag)); // [ '🇺🇳' ]
```

However, you can't use `\P` to match "a string that does not have a property", because it's unclear how many characters should be consumed.

```js
/\P{RGI\_Emoji\_Flag\_Sequence}/v; // SyntaxError: Invalid regular expression: Invalid property name
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-CharacterClassEscape |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Character classes guide
* Regular expressions
* Character class: `[...]`, `[^...]`
* Character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`
* Character escape: `\n`, `\u{...}`
* Disjunction: `|`
* Unicode character property on Wikipedia
* ES2018: RegExp Unicode property escapes by Dr. Axel Rauschmayer (2017)
* Unicode regular expressions § Properties
* Unicode Utilities: UnicodeSet
* RegExp v flag with set notation and properties of strings on v8.dev (2022)


Backreference: \1, \2 - JavaScript

Backreference: \1, \2
=====================

A **backreference** refers to the submatch of a previous capturing group and matches the same text as that group. For named capturing groups, you may prefer to use the named backreference syntax.

Syntax
------

```regex
\N
```

**Note:** `N` is not a literal character.

### Parameters

`N`

A positive integer referring to the number of a capturing group.

Description
-----------

A backreference is a way to match the same text as previously matched by a capturing group. Capturing groups count from 1, so the first capturing group's result can be referenced with `\1`, the second with `\2`, and so on. `\0` is a character escape for the NUL character.

In case-insensitive matching, the backreference may match text with different casing from the original text.

```js
/(b)\1/i.test("bB"); // true
```

The backreference must refer to an existent capturing group. If the number it specifies is greater than the total number of capturing groups, a syntax error is thrown.

```js
/(a)\2/u; // SyntaxError: Invalid regular expression: Invalid escape
```

In Unicode-unaware mode, invalid backreferences become a legacy octal escape sequence. This is a deprecated syntax for web compatibility, and you should not rely on it.

```js
/(a)\2/.test("a\x02"); // true
```

If the referenced capturing group is unmatched (for example, because it belongs to an unmatched alternative in a disjunction), or the group hasn't matched yet (for example, because it lies to the right of the backreference), the backreference always succeeds (as if it matches the empty string).

```js
/(?:a|(b))\1c/.test("ac"); // true
/\1(a)/.test("a"); // true
```

Examples
--------

### Pairing quotes

The following function matches the `title='xxx'` and `title="xxx"` patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group (`[2]`) returns the string between the matching quote characters:

```js
function parseTitle(metastring) {
  return metastring.match(/title=(["'])(.\*?)\1/)[2];
}

parseTitle('title="foo"'); // 'foo'
parseTitle("title='foo' lang='en'"); // 'foo'
parseTitle('title="Named capturing groups\' advantages"'); // "Named capturing groups' advantages"
```

### Matching duplicate words

The following function finds duplicate words in a string (which are usually typos). Note that it uses the `\w` character class escape, which only matches English letters but not any accented letters or other alphabets. If you want more generic matching, you may want to split the string by whitespace and iterate over the resulting array.

```js
function findDuplicates(text) {
  return text.match(/\b(\w+)\s+\1\b/i)?.[1];
}

findDuplicates("foo foo bar"); // 'foo'
findDuplicates("foo bar foo"); // undefined
findDuplicates("Hello hello"); // 'Hello'
findDuplicates("Hello hellos"); // undefined
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-DecimalEscape |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Groups and backreferences guide
* Regular expressions
* Capturing group: `(...)`
* Named capturing group: `(?<name>...)`
* Named backreference: `\k<name>`


Character class escape: \d, \D, \w, \W, \s, \S - JavaScript

Character class escape: \d, \D, \w, \W, \s, \S
==============================================

A **character class escape** is an escape sequence that represents a set of characters.

Syntax
------

```regex
\d, \D
\s, \S
\w, \W
```

**Note:** `,` is not part of the syntax.

Description
-----------

Unlike character escapes, character class escapes represent a predefined *set* of characters, much like a character class. The following character classes are supported:

`\d`

Matches any digit character. Equivalent to `[0-9]`.

`\w`

Matches any word character, where a word character includes letters (A–Z, a–z), numbers (0–9), and underscore (\_). If the regex is Unicode-aware and the `i` flag is set, it also matches other Unicode characters that get canonicalized to one of the characters above through case folding.

`\s`

Matches any whitespace or line terminator character.

The uppercase forms `\D`, `\W`, and `\S` create complement character classes for `\d`, `\w`, and `\s`, respectively. They match any character that is not in the set of characters matched by the lowercase form.

Unicode character class escapes start with `\p` and `\P`, but they are only supported in Unicode-aware mode. In Unicode-unaware mode, they are identity escapes for the `p` or `P` character.

Character class escapes can be used in character classes. However, they cannot be used as boundaries of character ranges, which is only allowed as a deprecated syntax for web compatibility, and you should not rely on it.

Examples
--------

### Splitting by whitespace

The following example splits a string into an array of words, supporting all kinds of whitespace separators:

```js
function splitWords(str) {
  return str.split(/\s+/);
}

splitWords(`Look at the stars
Look how they\tshine for you`);
// ['Look', 'at', 'the', 'stars', 'Look', 'how', 'they', 'shine', 'for', 'you']
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-CharacterClassEscape |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Character classes guide
* Regular expressions
* Character class: `[...]`, `[^...]`
* Unicode character class escape: `\p{...}`, `\P{...}`
* Character escape: `\n`, `\u{...}`
* Disjunction: `|`


Lookbehind assertion: (?<=...), (?<!...) - JavaScript

Lookbehind assertion: (?<=...), (?<!...)
========================================

A **lookbehind assertion** "looks behind": it attempts to match the previous input with the given pattern, but it does not consume any of the input — if the match is successful, the current position in the input stays the same. It matches each atom in its pattern in the reverse order.

Syntax
------

```regex
(?<=pattern)
(?<!pattern)
```

### Parameters

`pattern`

A pattern consisting of anything you may use in a regex literal, including a disjunction.

Description
-----------

A regular expression generally matches from left to right. This is why lookahead and lookbehind assertions are called as such — lookahead asserts what's on the right, and lookbehind asserts what's on the left.

In order for a `(?<=pattern)` assertion to succeed, the `pattern` must match the input immediately to the left of the current position, but the current position is not changed before matching the subsequent input. The `(?<!pattern)` form negates the assertion — it succeeds if the `pattern` does not match the input immediately to the left of the current position.

Lookbehind generally has the same semantics as lookahead — however, within a lookbehind assertion, the regular expression matches *backwards*. For example,

```js
/(?<=([ab]+)([bc]+))$/.exec("abc"); // ['', 'a', 'bc']
// Not ['', 'ab', 'c']
```

If the lookbehind matches from left to right, it should first greedily match `[ab]+`, which makes the first group capture `"ab"`, and the remaining `"c"` is captured by `[bc]+`. However, because `[bc]+` is matched first, it greedily grabs `"bc"`, leaving only `"a"` for `[ab]+`.

This behavior is reasonable — the matcher does not know where to *start* the match (because the lookbehind may not be fixed-length), but it does know where to *end* (at the current position). Therefore, it starts from the current position and works backwards. (Regexes in some other languages forbid non-fixed-length lookbehind to avoid this issue.)

For quantified capturing groups inside the lookbehind, the match furthest to the left of the input string — instead of the one on the right — is captured because of backward matching. See the capturing groups page for more information. Backreferences inside the lookbehind must appear on the *left* of the group it's referring to, also due to backward matching. However, disjunctions are still attempted left-to-right.

Examples
--------

### Matching strings without consuming them

Similar to lookaheads, lookbehinds can be used to match strings without consuming them so that only useful information is extracted. For example, the following regex matches the number in a price label:

```js
function getPrice(label) {
  return /(?<=\$)\d+(?:\.\d\*)?/.exec(label)?.[0];
}

getPrice("$10.53"); // "10.53"
getPrice("10.53"); // undefined
```

A similar effect can be achieved by capturing the submatch you are interested in.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Assertion |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Assertions guide
* Regular expressions
* Input boundary assertion: `^`, `$`
* Word boundary assertion: `\b`, `\B`
* Lookahead assertion: `(?=...)`, `(?!...)`
* Capturing group: `(...)`


Disjunction:

Disjunction: |
==============

A **disjunction** specifies multiple alternatives. Any alternative matching the input causes the entire disjunction to be matched.

Syntax
------

```regex
alternative1|alternative2
alternative1|alternative2|alternative3|…
```

### Parameters

`alternativeN`

One alternative pattern, composed of a sequence of atoms and assertions. Successfully matching one alternative causes the entire disjunction to be matched.

Description
-----------

The `|` regular expression operator separates two or more *alternatives*. The pattern first tries to match the first alternative; if it fails, it tries to match the second one, and so on. For example, the following matches `"a"` instead of `"ab"`, because the first alternative already matches successfully:

```js
/a|ab/.exec("abc"); // ['a']
```

The `|` operator has the lowest precedence in a regular expression. If you want to use a disjunction as a part of a bigger pattern, you must group it.

When a grouped disjunction has more expressions after it, the matching begins by selecting the first alternative and attempting to match the rest of the regular expression. If the rest of the regular expression fails to match, the matcher tries the next alternative instead. For example,

```js
/(?:(a)|(ab))(?:(c)|(bc))/.exec("abc"); // ['abc', 'a', undefined, undefined, 'bc']
// Not ['abc', undefined, 'ab', 'c', undefined]
```

This is because by selecting `a` in the first alternative, it's possible to select `bc` in the second alternative and result in a successful match. This process is called *backtracking*, because the matcher first goes beyond the disjunction and then comes back to it when subsequent matching fails.

Note also that any capturing parentheses inside an alternative that's not matched produce `undefined` in the resulting array.

An alternative can be empty, in which case it matches the empty string (in other words, always matches).

Alternatives are always attempted left-to-right, regardless of the direction of matching (which is reversed in a lookbehind).

Examples
--------

### Matching file extensions

The following example matches file extensions, using the same code as the input boundary assertion article:

```js
function isImage(filename) {
  return /\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);
}

isImage("image.png"); // true
isImage("image.jpg"); // true
isImage("image.pdf"); // false
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Disjunction |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Character classes guide
* Regular expressions
* Quantifier: `*`, `+`, `?`, `{n}`, `{n,}`, `{n,m}`
* Character class: `[...]`, `[^...]`


Named capturing group: (?<name>...) - JavaScript

Named capturing group: (?<name>...)
===================================

A **named capturing group** is a particular kind of capturing group that allows to give a name to the group. The group's matching result can later be identified by this name instead of by its index in the pattern.

Syntax
------

```regex
(?<name>pattern)
```

### Parameters

`pattern`

A pattern consisting of anything you may use in a regex literal, including a disjunction.

`name`

The name of the group. Must be a valid identifier.

Description
-----------

Named capturing groups can be used just like capturing groups — they also have their match index in the result array, and they can be referenced through `\1`, `\2`, etc. The only difference is that they can be *additionally* referenced by their name. The information of the capturing group's match can be accessed through:

* The `groups` property of the return value of `RegExp.prototype.exec()`, `String.prototype.match()`, and `String.prototype.matchAll()`
* The `groups` parameter of the `String.prototype.replace()` and `String.prototype.replaceAll()` methods' `replacement` callback function
* Named backreferences within the same pattern

All names must be unique within the same pattern. Multiple named capturing groups with the same name result in a syntax error.

```js
/(?<name>)(?<name>)/; // SyntaxError: Invalid regular expression: Duplicate capture group name
```

This restriction is relaxed if the duplicate named capturing groups are not in the same disjunction alternative, so for any string input, only one named capturing group can actually be matched. This is a much newer feature, so check browser compatibility before using it.

```js
/(?<year>\d{4})-\d{2}|\d{2}-(?<year>\d{4})/;
// Works; "year" can either come before or after the hyphen
```

Named capturing groups will all be present in the result. If a named capturing group is not matched (for example, it belongs to an unmatched alternative in a disjunction), the corresponding property on the `groups` object has value `undefined`.

```js
/(?<ab>ab)|(?<cd>cd)/.exec("cd").groups; // [Object: null prototype] { ab: undefined, cd: 'cd' }
```

You can get the start and end indices of each named capturing group in the input string by using the `d` flag. In addition to accessing them on the `indices` property on the array returned by `exec()`, you can also access them by their names on `indices.groups`.

Compared to unnamed capturing groups, named capturing groups have the following advantages:

* They allow you to provide a descriptive name for each submatch result.
* They allow you to access submatch results without having to remember the order in which they appear in the pattern.
* When refactoring code, you can change the order of capturing groups without worrying about breaking other references.
Examples
--------

### Using named capturing groups

The following example parses a timestamp and an author name from a Git log entry (output with `git log --format=%ct,%an -- filename`):

```js
function parseLog(entry) {
  const { author, timestamp } = /^(?<timestamp>\d+),(?<author>.+)$/.exec(
    entry,
  ).groups;
  return `${author} committed on ${new Date(
 parseInt(timestamp) \* 1000,
 ).toLocaleString()}`;
}

parseLog("1560979912,Caroline"); // "Caroline committed on 6/19/2019, 5:31:52 PM"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # prod-Atom |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of named capturing groups in `core-js`
* Groups and backreferences guide
* Regular expressions
* Capturing group: `(...)`
* Non-capturing group: `(?:...)`
* Named backreference: `\k<name>`
* ESLint rule: `prefer-named-capture-group`


Default parameters - JavaScript

Default parameters
==================

**Default function parameters** allow named parameters to be initialized with default values if no value or `undefined` is passed.

Try it
------

Syntax
------

```js
function fnName(param1 = defaultValue1, /\* …, \*/ paramN = defaultValueN) {
  // …
}
```

Description
-----------

In JavaScript, function parameters default to `undefined`. However, it's often useful to set a different default value. This is where default parameters can help.

In the following example, if no value is provided for `b` when `multiply` is called, `b`'s value would be `undefined` when evaluating `a * b` and `multiply` would return `NaN`.

```js
function multiply(a, b) {
  return a \* b;
}

multiply(5, 2); // 10
multiply(5); // NaN !
```

In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are `undefined`. In the following example, `b` is set to `1` if `multiply` is called with only one argument:

```js
function multiply(a, b) {
  b = typeof b !== "undefined" ? b : 1;
  return a \* b;
}

multiply(5, 2); // 10
multiply(5); // 5
```

With default parameters, checks in the function body are no longer necessary. Now, you can assign `1` as the default value for `b` in the function head:

```js
function multiply(a, b = 1) {
  return a \* b;
}

multiply(5, 2); // 10
multiply(5); // 5
multiply(5, undefined); // 5
```

Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.

```js
function f(x = 1, y) {
  return [x, y];
}

f(); // [1, undefined]
f(2); // [2, undefined]
```

**Note:** The first default parameter and all parameters after it will not contribute to the function's `length`.

The default parameter initializers live in their own scope, which is a parent of the scope created for the function body.

This means that earlier parameters can be referred to in the initializers of later parameters. However, functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time `ReferenceError`. This also includes `var`-declared variables in the function body.

For example, the following function will throw a `ReferenceError` when invoked, because the default parameter value does not have access to the child scope of the function body:

```js
function f(a = go()) {
  function go() {
    return ":P";
  }
}

f(); // ReferenceError: go is not defined
```

This function will print the value of the *parameter* `a`, because the variable `var a` is hoisted only to the top of the scope created for the function body, not the parent scope created for the parameter list, so its value is not visible to `b`.

```js
function f(a, b = () => console.log(a)) {
  var a = 1;
  b();
}

f(); // undefined
f(5); // 5
```

Examples
--------

### Passing undefined vs. other falsy values

In the second call in this example, even if the first argument is set explicitly to `undefined` (though not `null` or other falsy values), the value of the `num` argument is still the default.

```js
function test(num = 1) {
  console.log(typeof num);
}

test(); // 'number' (num is set to 1)
test(undefined); // 'number' (num is set to 1 too)

// test with other falsy values:
test(""); // 'string' (num is set to '')
test(null); // 'object' (num is set to null)
```

### Evaluated at call time

The default argument is evaluated at *call time*. Unlike with Python (for example), a new object is created each time the function is called.

```js
function append(value, array = []) {
  array.push(value);
  return array;
}

append(1); // [1]
append(2); // [2], not [1, 2]
```

This even applies to functions and variables:

```js
function callSomething(thing = something()) {
  return thing;
}

let numberOfTimesCalled = 0;
function something() {
  numberOfTimesCalled += 1;
  return numberOfTimesCalled;
}

callSomething(); // 1
callSomething(); // 2
```

### Earlier parameters are available to later default parameters

Parameters defined earlier (to the left) are available to later default parameters:

```js
function greet(name, greeting, message = `${greeting} ${name}`) {
  return [name, greeting, message];
}

greet("David", "Hi"); // ["David", "Hi", "Hi David"]
greet("David", "Hi", "Happy Birthday!"); // ["David", "Hi", "Happy Birthday!"]
```

This functionality can be approximated like this, which demonstrates how many edge cases are handled:

```js
function go() {
  return ":P";
}

function withDefaults(
  a,
 b = 5,
 c = b,
 d = go(),
 e = this,
 f = arguments,
 g = this.value,
) {
  return [a, b, c, d, e, f, g];
}

function withoutDefaults(a, b, c, d, e, f, g) {
  switch (arguments.length) {
    case 0:
    case 1:
      b = 5;
    case 2:
      c = b;
    case 3:
      d = go();
    case 4:
      e = this;
    case 5:
      f = arguments;
    case 6:
      g = this.value;
  }
  return [a, b, c, d, e, f, g];
}

withDefaults.call({ value: "=^\_^=" });
// [undefined, 5, 5, ":P", {value:"=^\_^="}, arguments, "=^\_^="]

withoutDefaults.call({ value: "=^\_^=" });
// [undefined, 5, 5, ":P", {value:"=^\_^="}, arguments, "=^\_^="]
```

### Destructured parameter with default value assignment

You can use default value assignment with the destructuring assignment syntax.

A common way of doing that is to set an empty object/array as the default value for the destructured parameter; for example: `[x = 1, y = 2] = []`. This makes it possible to pass nothing to the function and still have those values prefilled:

```js
function preFilledArray([x = 1, y = 2] = []) {
  return x + y;
}

preFilledArray(); // 3
preFilledArray([]); // 3
preFilledArray([2]); // 4
preFilledArray([2, 3]); // 5

// Works the same for objects:
function preFilledObject({ z = 3 } = {}) {
  return z;
}

preFilledObject(); // 3
preFilledObject({}); // 3
preFilledObject({ z: 2 }); // 2
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-function-definitions |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Functions guide
* Functions
* Rest parameters
* Nullish coalescing operator (`??`)