Object.getOwnPropertyNames() - JavaScript

Object.getOwnPropertyNames()
============================

The **`Object.getOwnPropertyNames()`** static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.

Try it
------

Syntax
------

```js
Object.getOwnPropertyNames(obj)
```

### Parameters

`obj`

The object whose enumerable and non-enumerable properties are to be returned.

### Return value

An array of strings that corresponds to the properties found directly in the given object.

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

`Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by `Object.keys()`) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion.

In ES5, if the argument to this method is not an object (a primitive), then it will cause a `TypeError`. In ES2015, a non-object argument will be coerced to an object.

```js
Object.getOwnPropertyNames("foo");
// TypeError: "foo" is not an object (ES5 code)

Object.getOwnPropertyNames("foo");
// ["0", "1", "2", "length"] (ES2015 code)
```

Examples
--------

### Using Object.getOwnPropertyNames()

```js
const arr = ["a", "b", "c"];
console.log(Object.getOwnPropertyNames(arr).sort());
// ["0", "1", "2", "length"]

// Array-like object
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.getOwnPropertyNames(obj).sort());
// ["0", "1", "2"]

Object.getOwnPropertyNames(obj).forEach((val, idx, array) => {
  console.log(`${val} -> ${obj[val]}`);
});
// 0 -> a
// 1 -> b
// 2 -> c

// non-enumerable property
const myObj = Object.create(
  {},
  {
    getFoo: {
      value() {
        return this.foo;
      },
      enumerable: false,
    },
  },
);
myObj.foo = 1;

console.log(Object.getOwnPropertyNames(myObj).sort()); // ["foo", "getFoo"]
```

If you want only the enumerable properties, see `Object.keys()` or use a `for...in` loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with `Object.hasOwn()`).

Items on the prototype chain are not listed:

```js
function ParentClass() {}
ParentClass.prototype.inheritedMethod = function () {};

function ChildClass() {
  this.prop = 5;
  this.method = function () {};
}
ChildClass.prototype = new ParentClass();
ChildClass.prototype.prototypeMethod = function () {};

console.log(Object.getOwnPropertyNames(new ChildClass()));
// ["prop", "method"]
```

### Get non-enumerable properties only

This uses the `Array.prototype.filter()` function to remove the enumerable keys (obtained with `Object.keys()`) from a list of all keys (obtained with `Object.getOwnPropertyNames()`) thus giving only the non-enumerable keys as output.

```js
const target = myObject;
const enumAndNonenum = Object.getOwnPropertyNames(target);
const enumOnly = new Set(Object.keys(target));
const nonenumOnly = enumAndNonenum.filter((key) => !enumOnly.has(key));

console.log(nonenumOnly);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.getownpropertynames |

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

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

See also
--------

* Polyfill of `Object.getOwnPropertyNames` in `core-js`
* Enumerability and ownership of properties
* `Object.hasOwn()`
* `Object.prototype.propertyIsEnumerable()`
* `Object.create()`
* `Object.keys()`
* `Array.prototype.forEach()`


Object.defineProperties() - JavaScript

Object.defineProperties()
=========================

 The **`Object.defineProperties()`** static method defines new or
 modifies existing properties directly on an object, returning the object.

Try it
------

Syntax
------

```js
Object.defineProperties(obj, props)
```

### Parameters

`obj`

The object on which to define or modify properties.

`props`

 An object whose keys represent the names of properties to be defined or modified and
 whose values are objects describing those properties. Each value in `props`
 must be either a data descriptor or an accessor descriptor; it cannot be both (see
 `Object.defineProperty()` for more details).

Data descriptors and accessor descriptors may optionally contain the following keys:

`configurable`

`true` if and only if the type of this property descriptor may be
 changed and if the property may be deleted from the corresponding object.
 **Defaults to `false`.**

`enumerable`

`true` if and only if this property shows up during enumeration of
 the properties on the corresponding object.
 **Defaults to `false`.**

A data descriptor also has the following optional keys:

`value`

 The value associated with the property. Can be any valid JavaScript value
 (number, object, function, etc.).
 **Defaults to `undefined`.**

`writable`

`true` if and only if the value associated with the property may be
 changed with an assignment operator.
 **Defaults to `false`.**

An accessor descriptor also has the following optional keys:

`get`

 A function which serves as a getter for the property, or `undefined`
 if there is no getter. The function's return value will be used as the value of
 the property.
 **Defaults to `undefined`.**

`set`

 A function which serves as a setter for the property, or `undefined`
 if there is no setter. The function will receive as its only argument the new
 value being assigned to the property.
 **Defaults to `undefined`.**

 If a descriptor has neither of `value`, `writable`,
 `get` and `set` keys, it is treated as a data descriptor. If a
 descriptor has both `value` or `writable` and `get`
 or `set` keys, an exception is thrown.

### Return value

The object that was passed to the function.

Examples
--------

### Using Object.defineProperties

```js
const obj = {};
Object.defineProperties(obj, {
  property1: {
    value: true,
    writable: true,
  },
  property2: {
    value: "Hello",
    writable: false,
  },
  // etc. etc.
});
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-object.defineproperties |

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

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

See also
--------

* Polyfill of `Object.defineProperties` in `core-js`
* `Object.defineProperty()`
* `Object.keys()`
* Enumerability and ownership of properties


RegExp.prototype.global - JavaScript

RegExp.prototype.global
=======================

The **`global`** accessor property of `RegExp` instances returns whether or not the `g` flag is used with this regular expression.

Try it
------

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

`RegExp.prototype.global` has the value `true` if the `g` flag was used; otherwise, `false`. The `g` flag indicates that the regular expression should be tested against all possible matches in a string. Each call to `exec()` will update its `lastIndex` property, so that the next call to `exec()` will start at the next character.

Some methods, such as `String.prototype.matchAll()` and `String.prototype.replaceAll()`, will validate that, if the parameter is a regex, it is global. The regex's `@@match` and `@@replace` methods (called by `String.prototype.match()` and `String.prototype.replace()`) would also have different behaviors when the regex is global.

The set accessor of `global` is `undefined`. You cannot change this property directly.

Examples
--------

### Using global

```js
const regex = /foo/g;
console.log(regex.global); // true

const str = "fooexamplefoo";
const str1 = str.replace(regex, "");
console.log(str1); // example

const regex1 = /foo/;
const str2 = str.replace(regex1, "");
console.log(str2); // examplefoo
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.global |

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

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

See also
--------

* `RegExp.prototype.lastIndex`
* `RegExp.prototype.dotAll`
* `RegExp.prototype.hasIndices`
* `RegExp.prototype.ignoreCase`
* `RegExp.prototype.multiline`
* `RegExp.prototype.source`
* `RegExp.prototype.sticky`
* `RegExp.prototype.unicode`


RegExp.leftContext ($`) - JavaScript

RegExp.leftContext ($`)
=======================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The **`RegExp.leftContext`** static accessor property returns the substring preceding the most recent match. `RegExp["$`"]` is an alias for this property.

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

Because `leftContext` is a static property of `RegExp`, you always use it as `RegExp.leftContext` or `RegExp["$`"]`, rather than as a property of a `RegExp` object you created.

The value of `leftContext` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `leftContext` is an empty string. The set accessor of `leftContext` is `undefined`, so you cannot change this property directly.

You cannot use the shorthand alias with the dot property accessor (`RegExp.$`` ), because ``` is not a valid identifier part, so this causes a `SyntaxError`. Use the bracket notation instead.

`$`` can also be used in the replacement string of `String.prototype.replace()`, but that's unrelated to the `RegExp["$`"]` legacy property.

Examples
--------

### Using leftContext and $`

```js
const re = /world/g;
re.test("hello world!");
RegExp.leftContext; // "hello "
RegExp["$`"]; // "hello "
```

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

| Specification |
| --- |
| Legacy RegExp features # additional-properties-of-the-regexp-constructor |

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

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

See also
--------

* `RegExp.input ($_)`
* `RegExp.lastMatch ($&)`
* `RegExp.lastParen ($+)`
* `RegExp.rightContext ($')`
* `RegExp.$1, …, RegExp.$9`


RegExp.prototype.toString() - JavaScript

RegExp.prototype.toString()
===========================

The **`toString()`** method of `RegExp` instances returns a string representing this regular expression.

Try it
------

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the given object.

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

The `RegExp` object overrides the `toString()` method of the `Object` object; it does not inherit `Object.prototype.toString()`. For `RegExp` objects, the `toString()` method returns a string representation of the regular expression.

In practice, it reads the regex's `source` and `flags` properties and returns a string in the form `/source/flags`. The `toString()` return value is guaranteed to be a parsable regex literal, although it may not be the exact same text as what was originally specified for the regex (for example, the flags may be reordered).

Examples
--------

### Using toString()

The following example displays the string value of a `RegExp` object:

```js
const myExp = new RegExp("a+b+c");
console.log(myExp.toString()); // '/a+b+c/'

const foo = new RegExp("bar", "g");
console.log(foo.toString()); // '/bar/g'
```

### Empty regular expressions and escaping

Since `toString()` accesses the `source` property, an empty regular expression returns the string `"/(?:)/"`, and line terminators such as `\n` are escaped. This makes the returned value always a valid regex literal.

```js
new RegExp().toString(); // "/(?:)/"

new RegExp("\n").toString() === "/\\n/"; // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp.prototype.tostring |

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

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

See also
--------

* `Object.prototype.toString()`


RegExp.prototype.unicodeSets - JavaScript

RegExp.prototype.unicodeSets
============================

The **`unicodeSets`** accessor property of `RegExp` instances returns whether or not the `v` flag is used with this regular expression.

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

`RegExp.prototype.unicodeSets` has the value `true` if the `v` flag was used; otherwise, `false`. The `v` flag is an "upgrade" to the `u` flag that enables more Unicode-related features. ("v" is the next letter after "u" in the alphabet.) Because `u` and `v` interpret the same regex in incompatible ways, using both flags results in a `SyntaxError`. With the `v` flag, you get all features mentioned in the `u` flag description, plus:

* The `\p` escape sequence can be additionally used to match properties of strings, instead of just characters.
* The character class syntax is upgraded to allow intersection, union, and subtraction syntaxes, as well as matching multiple Unicode characters.
* The character class complement syntax `[^...]` constructs a complement class instead of negating the match result, avoiding some confusing behaviors with case-insensitive matching. For more information, see Complement classes and case-insensitive matching.

Some valid `u`-mode regexes become invalid in `v`-mode. Specifically, the character class syntax is different and some characters can no longer appear literally. For more information, see `v`-mode character class.

**Note:** The `v` mode does not interpret grapheme clusters as single characters; they are still multiple code points. For example, `/[🇺🇳]/v` is still able to match `"🇺"`.

The set accessor of `unicodeSets` is `undefined`. You cannot change this property directly.

Examples
--------

### Using the unicodeSets property

```js
const regex = /[\p{Script\_Extensions=Greek}&&\p{Letter}]/v;

console.log(regex.unicodeSets); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.unicodesets |

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

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

See also
--------

* `RegExp.prototype.lastIndex`
* `RegExp.prototype.dotAll`
* `RegExp.prototype.global`
* `RegExp.prototype.hasIndices`
* `RegExp.prototype.ignoreCase`
* `RegExp.prototype.multiline`
* `RegExp.prototype.source`
* `RegExp.prototype.sticky`
* `RegExp.prototype.unicode`
* RegExp v flag with set notation and properties of strings on v8.dev (2022)


RegExp.prototype[@@search]() - JavaScript

RegExp.prototype[@@search]()
============================

The **`[@@search]()`** method of `RegExp` instances specifies how `String.prototype.search` should behave.

Try it
------

Syntax
------

```js
regexp[Symbol.search](str)
```

### Parameters

`str`

A `String` that is a target of the search.

### Return value

The index of the first match between the regular expression and the given string, or `-1` if no match was found.

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

This method is called internally in `String.prototype.search()`. For example, the following two examples return the same result.

```js
"abc".search(/a/);

/a/[Symbol.search]("abc");
```

This method does not copy the regular expression, unlike `@@split` or `@@matchAll`. However, unlike `@@match` or `@@replace`, it will set `lastIndex` to 0 when execution starts and restore it to the previous value when it exits, therefore generally avoiding side effects. This means that the `g` flag has no effect with this method, and it always returns the first match in the string even when `lastIndex` is non-zero. This also means sticky regexps will always search strictly at the beginning of the string.

```js
const re = /[abc]/g;
re.lastIndex = 2;
console.log("abc".search(re)); // 0

const re2 = /[bc]/y;
re2.lastIndex = 1;
console.log("abc".search(re2)); // -1
console.log("abc".match(re2)); // [ 'b' ]
```

`@@search` always calls the regex's `exec()` method exactly once, and returns the `index` property of the result, or `-1` if the result is `null`.

This method exists for customizing the search behavior in `RegExp` subclasses.

Examples
--------

### Direct call

This method can be used in almost the same way as `String.prototype.search()`, except for the different value of `this` and the different arguments order.

```js
const re = /-/g;
const str = "2016-01-02";
const result = re[Symbol.search](str);
console.log(result); // 4
```

### Using @@search in subclasses

Subclasses of `RegExp` can override `[@@search]()` method to modify the behavior.

```js
class MyRegExp extends RegExp {
  constructor(str) {
    super(str);
    this.pattern = str;
  }
  [Symbol.search](str) {
    return str.indexOf(this.pattern);
  }
}

const re = new MyRegExp("a+b");
const str = "ab a+b";
const result = str.search(re); // String.prototype.search calls re[@@search].
console.log(result); // 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp.prototype-@@search |

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

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

See also
--------

* Polyfill of `RegExp.prototype[@@search]` in `core-js`
* `String.prototype.search()`
* `RegExp.prototype[@@match]()`
* `RegExp.prototype[@@matchAll]()`
* `RegExp.prototype[@@replace]()`
* `RegExp.prototype[@@split]()`
* `RegExp.prototype.exec()`
* `RegExp.prototype.test()`
* `Symbol.search`


RegExp.prototype.source - JavaScript

RegExp.prototype.source
=======================

The **`source`** accessor property of `RegExp` instances returns a string containing the source text of this regular expression, without the two forward slashes on both sides or any flags.

Try it
------

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

Conceptually, the `source` property is the text between the two forward slashes in the regular expression literal. The language requires the returned string to be properly escaped, so that when the `source` is concatenated with a forward slash on both ends, it would form a parsable regex literal. For example, for `new RegExp("/")`, the `source` is `\\/`, because if it generates `/`, the resulting literal becomes `///`, which is a line comment. Similarly, all line terminators will be escaped because line terminator *characters* would break up the regex literal. There's no requirement for other characters, as long as the result is parsable. For empty regular expressions, the string `(?:)` is returned.

Examples
--------

### Using source

```js
const regex = /fooBar/gi;

console.log(regex.source); // "fooBar", doesn't contain /.../ and "gi".
```

### Empty regular expressions and escaping

```js
new RegExp().source; // "(?:)"

new RegExp("\n").source === "\\n"; // true, starting with ES5
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.source |

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

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

See also
--------

* `RegExp.prototype.flags`


RegExp.input ($_) - JavaScript

RegExp.input ($\_)
==================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The **`RegExp.input`** static accessor property returns the string against which a regular expression is matched. `RegExp.$_` is an alias for this property.

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

Because `input` is a static property of `RegExp`, you always use it as `RegExp.input` or `RegExp.$_`, rather than as a property of a `RegExp` object you created.

The value of `input` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `input` is an empty string. You can set the value of `input`, but this does not affect other behaviors of the regex, and the value will be overwritten again when the next successful match is made.

Examples
--------

### Using input and $\_

```js
const re = /hi/g;
re.test("hi there!");
RegExp.input; // "hi there!"
re.test("foo"); // new test, non-matching
RegExp.$_; // "hi there!"
re.test("hi world!"); // new test, matching
RegExp.$_; // "hi world!"
```

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

| Specification |
| --- |
| Legacy RegExp features # additional-properties-of-the-regexp-constructor |

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

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

See also
--------

* `RegExp.lastMatch ($&)`
* `RegExp.lastParen ($+)`
* `RegExp.leftContext ($`)`
* `RegExp.rightContext ($')`
* `RegExp.$1, …, RegExp.$9`


RegExp.prototype.sticky - JavaScript

RegExp.prototype.sticky
=======================

The **`sticky`** accessor property of `RegExp` instances returns whether or not the `y` flag is used with this regular expression.

Try it
------

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

`RegExp.prototype.sticky` has the value `true` if the `y` flag was used; otherwise, `false`. The `y` flag indicates that the regex attempts to match the target string only from the index indicated by the `lastIndex` property (and unlike a global regex, does not attempt to match from any later indexes).

The set accessor of `sticky` is `undefined`. You cannot change this property directly.

For both sticky regexes and global regexes:

* They start matching at `lastIndex`.
* When the match succeeds, `lastIndex` is advanced to the end of the match.
* When `lastIndex` is out of bounds of the currently matched string, `lastIndex` is reset to 0.

However, for the `exec()` method, the behavior when matching fails is different:

* When the `exec()` method is called on a sticky regex, if the regex fails to match at `lastIndex`, the regex immediately returns `null` and resets `lastIndex` to 0.
* When the `exec()` method is called on a global regex, if the regex fails to match at `lastIndex`, it tries to match from the next character, and so on until a match is found or the end of the string is reached.

For the `exec()` method, a regex that's both sticky and global behaves the same as a sticky and non-global regex. Because `test()` is a simple wrapper around `exec()`, `test()` would ignore the global flag and perform sticky matches as well. However, due to many other methods special-casing the behavior of global regexes, the global flag is, in general, orthogonal to the sticky flag.

* `String.prototype.matchAll()` (which calls `RegExp.prototype[@@matchAll]()`): `y`, `g` and `gy` are all different.
    + For `y` regexes: `matchAll()` throws; `[@@matchAll]()` yields the `exec()` result exactly once, without updating the regex's `lastIndex`.
    + For `g` or `gy` regexes: returns an iterator that yields a sequence of `exec()` results.
* `String.prototype.match()` (which calls `RegExp.prototype[@@match]()`): `y`, `g` and `gy` are all different.
    + For `y` regexes: returns the `exec()` result and updates the regex's `lastIndex`.
    + For `g` or `gy` regexes: returns an array of all `exec()` results.
* `String.prototype.search()` (which calls `RegExp.prototype[@@search]()`): the `g` flag is always irrelevant.
    + For `y` or `gy` regexes: always returns `0` (if the very beginning of the string matches) or `-1` (if the beginning doesn't match), without updating the regex's `lastIndex` when it exits.
    + For `g` regexes: returns the index of the first match in the string, or `-1` if no match is found.
* `String.prototype.split()` (which calls `RegExp.prototype[@@split]()`): `y`, `g`, and `gy` all have the same behavior.
* `String.prototype.replace()` (which calls `RegExp.prototype[@@replace]()`): `y`, `g` and `gy` are all different.
    + For `y` regexes: replaces once at the current `lastIndex` and updates `lastIndex`.
    + For `g` and `gy` regexes: replaces all occurrences matched by `exec()`.
* `String.prototype.replaceAll()` (which calls `RegExp.prototype[@@replace]()`): `y`, `g` and `gy` are all different.
    + For `y` regexes: `replaceAll()` throws.
    + For `g` and `gy` regexes: replaces all occurrences matched by `exec()`.
Examples
--------

### Using a regular expression with the sticky flag

```js
const str = "#foo#";
const regex = /foo/y;

regex.lastIndex = 1;
regex.test(str); // true
regex.lastIndex = 5;
regex.test(str); // false (lastIndex is taken into account with sticky flag)
regex.lastIndex; // 0 (reset after match failure)
```

### Anchored sticky flag

For several versions, Firefox's SpiderMonkey engine had a bug with regard to the `^` assertion and the sticky flag which allowed expressions starting with the `^` assertion and using the sticky flag to match when they shouldn't. The bug was introduced some time after Firefox 3.6 (which had the sticky flag but not the bug) and fixed in 2015. Perhaps because of the bug, the specification specifically calls out the fact that:

>
> Even when the `y` flag is used with a pattern, `^` always matches only at the beginning of *Input*, or (if *rer*.[[Multiline]] is `true`) at the beginning of a line.
>
>
>

Examples of correct behavior:

```js
const regex = /^foo/y;
regex.lastIndex = 2;
regex.test("..foo"); // false - index 2 is not the beginning of the string

const regex2 = /^foo/my;
regex2.lastIndex = 2;
regex2.test("..foo"); // false - index 2 is not the beginning of the string or line
regex2.lastIndex = 2;
regex2.test(".\nfoo"); // true - index 2 is the beginning of a line
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.sticky |

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

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

See also
--------

* Polyfill of the `sticky` flag in `core-js`
* `RegExp.prototype.lastIndex`
* `RegExp.prototype.dotAll`
* `RegExp.prototype.global`
* `RegExp.prototype.hasIndices`
* `RegExp.prototype.ignoreCase`
* `RegExp.prototype.multiline`
* `RegExp.prototype.source`
* `RegExp.prototype.unicode`


RegExp() constructor - JavaScript

RegExp() constructor
====================

The **`RegExp()`** constructor creates `RegExp` objects.

For an introduction to regular expressions, read the Regular Expressions chapter in the JavaScript Guide.

Try it
------

Syntax
------

```js
new RegExp(pattern)
new RegExp(pattern, flags)
RegExp(pattern)
RegExp(pattern, flags)
```

**Note:** `RegExp()` can be called with or without `new`, but sometimes with different effects. See Return value.

### Parameters

`pattern`

The text of the regular expression. This can also be another `RegExp` object.

`flags` Optional

If specified, `flags` is a string that contains the flags to add. Alternatively, if a `RegExp` object is supplied for the `pattern`, the `flags` string will replace any of that object's flags (and `lastIndex` will be reset to `0`).

`flags` may contain any combination of the following characters:

`d` (indices)

Generate indices for substring matches.

`g` (global)

Find all matches rather than stopping after the first match.

`i` (ignore case)

When matching, casing differences are ignored.

`m` (multiline)

Treat beginning and end assertions (`^` and `$`) as working over multiple lines. In other words, match the beginning or end of *each* line (delimited by `\n` or `\r`), not only the very beginning or end of the whole input string.

`s` (dotAll)

Allows `.` to match newlines.

`u` (unicode)

Treat `pattern` as a sequence of Unicode code points.

`v` (unicodeSets)

An upgrade to the `u` flag that enables set notation in character classes as well as properties of strings.

`y` (sticky)

Matches only from the index indicated by the `lastIndex` property of this regular expression in the target string. Does not attempt to match from any later indexes.

### Return value

`RegExp(pattern)` returns `pattern` directly if all of the following are true:

* `RegExp()` is called without `new`;
* `pattern` is a regex;
* `pattern.constructor === RegExp` (usually meaning it's not a subclass);
* `flags` is `undefined`.

In all other cases, calling `RegExp()` with or without `new` both create a new `RegExp` object. If `pattern` is a regex, the new object's source is `pattern.source`; otherwise, its source is `pattern` coerced to a string. If the `flags` parameter is not `undefined`, the new object's `flags` is the parameter's value; otherwise, its `flags` is `pattern.flags` (if `pattern` is a regex).

### Exceptions

`SyntaxError`

Thrown in one of the following cases:

* `pattern` cannot be parsed as a valid regular expression.
* `flags` contains repeated characters or any character outside of those allowed.

Examples
--------

### Literal notation and constructor

There are two ways to create a `RegExp` object: a *literal notation* and a *constructor*.

* The *literal notation* takes a pattern between two slashes, followed by optional flags, after the second slash.
* The *constructor function* takes either a string or a `RegExp` object as its first parameter and a string of optional flags as its second parameter.

The following three expressions create the same regular expression:

```js
/ab+c/i;
new RegExp(/ab+c/, "i"); // literal notation
new RegExp("ab+c", "i"); // constructor
```

Before regular expressions can be used, they have to be compiled. This process allows them to perform matches more efficiently. There are two ways to compile and get a `RegExp` object.

The literal notation results in compilation of the regular expression when the expression is evaluated. On the other hand, the constructor of the `RegExp` object, `new RegExp('ab+c')`, results in runtime compilation of the regular expression.

Use a string as the first argument to the `RegExp()` constructor when you want to build the regular expression from dynamic input.

### Building a regular expression from dynamic inputs

```js
const breakfasts = ["bacon", "eggs", "oatmeal", "toast", "cereal"];
const order = "Let me get some bacon and eggs, please";

order.match(new RegExp(`\\b(${breakfasts.join("|")})\\b`, "g"));
// Returns ['bacon', 'eggs']
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp-constructor |

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

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

See also
--------

* Polyfill of many modern `RegExp` features (`dotAll`, `sticky` flags, named capture groups, etc.) in `core-js`
* Regular expressions guide
* `String.prototype.match()`
* `String.prototype.replace()`


RegExp.prototype.compile() - JavaScript

RegExp.prototype.compile()
==========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** The `compile()` method is only specified for compatibility reasons. Using `compile()` causes the otherwise immutable regex source and flags to become mutable, which may break user expectations. You can use the `RegExp()` constructor to construct a new regular expression object instead.

The **`compile()`** method of `RegExp` instances is used to recompile a regular expression with new source and flags after the `RegExp` object has already been created.

Syntax
------

```js
compile(pattern, flags)
```

### Parameters

`pattern`

The text of the regular expression.

`flags`

Any combination of flag values.

### Return value

None (`undefined`).

Examples
--------

### Using compile()

The following example shows how to recompile a regular expression with a new pattern and a new flag.

```js
const regexObj = new RegExp("foo", "gi");
regexObj.compile("new foo", "g");
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp.prototype.compile |

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

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

See also
--------

* `RegExp`


RegExp.lastParen ($+) - JavaScript

RegExp.lastParen ($+)
=====================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The **`RegExp.lastParen`** static accessor property returns the last parenthesized substring match, if any. `RegExp["$+"]` is an alias for this property.

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

Because `lastParen` is a static property of `RegExp`, you always use it as `RegExp.lastParen` or `RegExp["$+"]`, rather than as a property of a `RegExp` object you created.

The value of `lastParen` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, or if the most recent regex execution contains no capturing groups, `lastParen` is an empty string. The set accessor of `lastParen` is `undefined`, so you cannot change this property directly.

You cannot use the shorthand alias with the dot property accessor (`RegExp.$+`), because `+` is not a valid identifier part, so this causes a `SyntaxError`. Use the bracket notation instead.

Examples
--------

### Using lastParen and $+

```js
const re = /(hi)/g;
re.test("hi there!");
RegExp.lastParen; // "hi"
RegExp["$+"]; // "hi"
```

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

| Specification |
| --- |
| Legacy RegExp features # additional-properties-of-the-regexp-constructor |

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

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

See also
--------

* `RegExp.input ($_)`
* `RegExp.lastMatch ($&)`
* `RegExp.leftContext ($`)`
* `RegExp.rightContext ($')`
* `RegExp.$1, …, RegExp.$9`


RegExp.prototype.dotAll - JavaScript

RegExp.prototype.dotAll
=======================

The **`dotAll`** accessor property of `RegExp` instances returns whether or not the `s` flag is used with this regular expression.

Try it
------

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

`RegExp.prototype.dotAll` has the value `true` if the `s` flag was used; otherwise, `false`. The `s` flag indicates that the dot special character (`.`) should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise:

* U+000A LINE FEED (LF) (`\n`)
* U+000D CARRIAGE RETURN (CR) (`\r`)
* U+2028 LINE SEPARATOR
* U+2029 PARAGRAPH SEPARATOR

This effectively means the dot will match any character on the Unicode Basic Multilingual Plane (BMP). To allow it to match astral characters, the `u` (unicode) flag should be used. Using both flags in conjunction allows the dot to match any Unicode character, without exceptions.

The set accessor of `dotAll` is `undefined`. You cannot change this property directly.

Examples
--------

### Using dotAll

```js
const str1 = "bar\nexample foo example";

const regex1 = /bar.example/s;

console.log(regex1.dotAll); // true

console.log(str1.replace(regex1, "")); // foo example

const str2 = "bar\nexample foo example";

const regex2 = /bar.example/;

console.log(regex2.dotAll); // false

console.log(str2.replace(regex2, ""));
// bar
// example foo example
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.dotAll |

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

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

See also
--------

* Polyfill of the `dotAll` flag in `core-js`
* `RegExp.prototype.lastIndex`
* `RegExp.prototype.global`
* `RegExp.prototype.hasIndices`
* `RegExp.prototype.ignoreCase`
* `RegExp.prototype.multiline`
* `RegExp.prototype.source`
* `RegExp.prototype.sticky`
* `RegExp.prototype.unicode`


RegExp.prototype[@@split]() - JavaScript

RegExp.prototype[@@split]()
===========================

The **`[@@split]()`** method of `RegExp` instances specifies how `String.prototype.split` should behave when the regular expression is passed in as the separator.

Try it
------

Syntax
------

```js
regexp[Symbol.split](str)
regexp[Symbol.split](str, limit)
```

### Parameters

`str`

The target of the split operation.

`limit` Optional

Integer specifying a limit on the number of splits to be found. The `[@@split]()` method still splits on every match of `this` RegExp pattern (or, in the Syntax above, `regexp`), until the number of split items match the `limit` or the string falls short of `this` pattern.

### Return value

An `Array` containing substrings as its elements. Capturing groups are included.

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

This method is called internally in `String.prototype.split()` when a `RegExp` is passed as the separator. For example, the following two examples return the same result.

```js
"a-b-c".split(/-/);

/-/[Symbol.split]("a-b-c");
```

This method exists for customizing the behavior of `split()` in `RegExp` subclasses.

The `RegExp.prototype[@@split]()` base method exhibits the following behaviors:

* It starts by using `@@species` to construct a new regexp, thus avoiding mutating the original regexp in any way.
* The regexp's `g` ("global") flag is ignored, and the `y` ("sticky") flag is always applied even when it was not originally present.
* If the target string is empty, and the regexp can match empty strings (for example, `/a?/`), an empty array is returned. Otherwise, if the regexp can't match an empty string, `[""]` is returned.
* The matching proceeds by continuously calling `this.exec()`. Since the regexp is always sticky, this will move along the string, each time yielding a matching string, index, and any capturing groups.
* For each match, the substring between the last matched string's end and the current matched string's beginning is first appended to the result array. Then, the capturing groups' values are appended one-by-one.
* If the current match is an empty string, or if the regexp doesn't match at the current position (since it's sticky), the `lastIndex` would still be advanced — if the regex is Unicode-aware, it would advance by one Unicode code point; otherwise, it advances by one UTF-16 code unit.
* If the regexp doesn't match the target string, the target string is returned as-is, wrapped in an array.
* The returned array's length will never exceed the `limit` parameter, if provided, while trying to be as close as possible. Therefore, the last match and its capturing groups may not all be present in the returned array if the array is already filled.
Examples
--------

### Direct call

 This method can be used in almost the same way as
 `String.prototype.split()`, except the different `this` and the
 different order of arguments.

```js
const re = /-/g;
const str = "2016-01-02";
const result = re[Symbol.split](str);
console.log(result); // ["2016", "01", "02"]
```

### Using @@split in subclasses

 Subclasses of `RegExp` can override the `[@@split]()` method to
 modify the default behavior.

```js
class MyRegExp extends RegExp {
  [Symbol.split](str, limit) {
    const result = RegExp.prototype[Symbol.split].call(this, str, limit);
    return result.map((x) => `(${x})`);
  }
}

const re = new MyRegExp("-");
const str = "2016-01-02";
const result = str.split(re); // String.prototype.split calls re[@@split].
console.log(result); // ["(2016)", "(01)", "(02)"]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp.prototype-@@split |

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

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

See also
--------

* Polyfill of `RegExp.prototype[@@split]` in `core-js`
* `String.prototype.split()`
* `RegExp.prototype[@@match]()`
* `RegExp.prototype[@@matchAll]()`
* `RegExp.prototype[@@replace]()`
* `RegExp.prototype[@@search]()`
* `RegExp.prototype.exec()`
* `RegExp.prototype.test()`
* `Symbol.split`


RegExp.prototype[@@replace]() - JavaScript

RegExp.prototype[@@replace]()
=============================

The **`[@@replace]()`** method of `RegExp` instances specifies how `String.prototype.replace()` and `String.prototype.replaceAll()` should behave when the regular expression is passed in as the pattern.

Try it
------

Syntax
------

```js
regexp[Symbol.replace](str, replacement)
```

### Parameters

`str`

A `String` that is a target of the replacement.

`replacement`

Can be a string or a function.

* If it's a string, it will replace the substring matched by the current regexp. A number of special replacement patterns are supported; see the Specifying a string as the replacement section of `String.prototype.replace`.
* If it's a function, it will be invoked for every match and the return value is used as the replacement text. The arguments supplied to this function are described in the Specifying a function as the replacement section of `String.prototype.replace`.

### Return value

A new string, with one, some, or all matches of the pattern replaced by the specified replacement.

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

This method is called internally in `String.prototype.replace()` and `String.prototype.replaceAll()` if the `pattern` argument is a `RegExp` object. For example, the following two examples return the same result.

```js
"abc".replace(/a/, "A");

/a/[Symbol.replace]("abc", "A");
```

If the regex is global (with the `g` flag), the regex's `exec()` method will be repeatedly called until `exec()` returns `null`. Otherwise, `exec()` would only be called once. For each `exec()` result, the substitution will be prepared based on the description in `String.prototype.replace()`.

Because `@@replace` would keep calling `exec()` until it returns `null`, and `exec()` would automatically reset the regex's `lastIndex` to 0 when the last match fails, `@@replace` would typically not have side effects when it exits. However, when the regex is sticky but not global, `lastIndex` would not be reset. In this case, each call to `replace()` may return a different result.

```js
const re = /a/y;

for (let i = 0; i < 5; i++) {
  console.log("aaa".replace(re, "b"), re.lastIndex);
}

// baa 1
// aba 2
// aab 3
// aaa 0
// baa 1
```

When the regex is sticky and global, it would still perform sticky matches — i.e. it would fail to match any occurrences beyond the `lastIndex`.

```js
console.log("aa-a".replace(/a/gy, "b")); // "bb-a"
```

If the current match is an empty string, the `lastIndex` would still be advanced — if the regex is Unicode-aware, it would advance by one Unicode code point; otherwise, it advances by one UTF-16 code unit.

```js
console.log("😄".replace(/(?:)/g, " ")); // " \ud83d \ude04 "
console.log("😄".replace(/(?:)/gu, " ")); // " 😄 "
```

This method exists for customizing replace behavior in `RegExp` subclasses.

Examples
--------

### Direct call

This method can be used in almost the same way as `String.prototype.replace()`, except the different `this` and the different arguments order.

```js
const re = /-/g;
const str = "2016-01-01";
const newstr = re[Symbol.replace](str, ".");
console.log(newstr); // 2016.01.01
```

### Using @@replace in subclasses

Subclasses of `RegExp` can override the `[@@replace]()` method to modify the default behavior.

```js
class MyRegExp extends RegExp {
  constructor(pattern, flags, count) {
    super(pattern, flags);
    this.count = count;
  }
  [Symbol.replace](str, replacement) {
    // Perform @@replace |count| times.
    let result = str;
    for (let i = 0; i < this.count; i++) {
      result = RegExp.prototype[Symbol.replace].call(this, result, replacement);
    }
    return result;
  }
}

const re = new MyRegExp("\\d", "", 3);
const str = "01234567";
const newstr = str.replace(re, "#"); // String.prototype.replace calls re[@@replace].
console.log(newstr); // ###34567
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp.prototype-@@replace |

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

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

See also
--------

* Polyfill of `RegExp.prototype[@@replace]` in `core-js`
* `String.prototype.replace()`
* `String.prototype.replaceAll()`
* `RegExp.prototype[@@match]()`
* `RegExp.prototype[@@matchAll]()`
* `RegExp.prototype[@@search]()`
* `RegExp.prototype[@@split]()`
* `RegExp.prototype.exec()`
* `RegExp.prototype.test()`
* `Symbol.replace`


RegExp.rightContext ($') - JavaScript

RegExp.rightContext ($')
========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The **`RegExp.rightContext`** static accessor property returns the substring following the most recent match. `RegExp["$'"]` is an alias for this property.

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

Because `rightContext` is a static property of `RegExp`, you always use it as `RegExp.rightContext` or `RegExp["$'"]`, rather than as a property of a `RegExp` object you created.

The value of `rightContext` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `rightContext` is an empty string. The set accessor of `rightContext` is `undefined`, so you cannot change this property directly.

You cannot use the shorthand alias with the dot property accessor (`RegExp.$'`), because `'` is not a valid identifier part, so this causes a `SyntaxError`. Use the bracket notation instead.

`$'` can also be used in the replacement string of `String.prototype.replace()`, but that's unrelated to the `RegExp["$'"]` legacy property.

Examples
--------

### Using rightContext and $'

```js
const re = /hello/g;
re.test("hello world!");
RegExp.rightContext; // " world!"
RegExp["$'"]; // " world!"
```

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

| Specification |
| --- |
| Legacy RegExp features # additional-properties-of-the-regexp-constructor |

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

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

See also
--------

* `RegExp.input ($_)`
* `RegExp.lastMatch ($&)`
* `RegExp.lastParen ($+)`
* `RegExp.leftContext ($`)`
* `RegExp.$1, …, RegExp.$9`


RegExp[@@species] - JavaScript

RegExp[@@species]
=================

The **`RegExp[@@species]`** static accessor property returns the constructor used to construct copied regular expressions in certain `RegExp` methods.

**Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

Try it
------

Syntax
------

```js
RegExp[Symbol.species]
```

### Return value

The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct copied `RegExp` instances.

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

The `@@species` accessor property returns the default constructor for `RegExp` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

```js
// Hypothetical underlying implementation for illustration
class RegExp {
  static get [Symbol.species]() {
    return this;
  }
}
```

Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default.

```js
class SubRegExp extends SubRegExp {}
SubRegExp[Symbol.species] === SubRegExp; // true
```

Some `RegExp` methods create a copy of the current regex instance before running `exec()`, so that side effects such as changes to `lastIndex` are not retained. The `@@species` property is used to determine the constructor of the new instance. The methods that copy the current regex instance are:

* `[@@matchAll]()`
* `[@@split]()`
Examples
--------

### Species in ordinary objects

The `@@species` property returns the default constructor function, which is the `RegExp` constructor for `RegExp` objects:

```js
RegExp[Symbol.species]; // function RegExp()
```

### Species in derived objects

In an instance of a custom `RegExp` subclass, such as `MyRegExp`, the `MyRegExp` species is the `MyRegExp` constructor. However, you might want to overwrite this, in order to return parent `RegExp` objects in your derived class methods:

```js
class MyRegExp extends RegExp {
  // Overwrite MyRegExp species to the parent RegExp constructor
  static get [Symbol.species]() {
    return RegExp;
  }
}
```

Or you can use this to observe the copying process:

```js
class MyRegExp extends RegExp {
  constructor(...args) {
    console.log("Creating a new MyRegExp instance with args:", args);
    super(...args);
  }
  static get [Symbol.species]() {
    console.log("Copying MyRegExp");
    return this;
  }
  exec(value) {
    console.log("Executing with lastIndex:", this.lastIndex);
    return super.exec(value);
  }
}

Array.from("aabbccdd".matchAll(new MyRegExp("[ac]", "g")));
// Creating a new MyRegExp instance with args: [ '[ac]', 'g' ]
// Copying MyRegExp
// Creating a new MyRegExp instance with args: [ MyRegExp /[ac]/g, 'g' ]
// Executing with lastIndex: 0
// Executing with lastIndex: 1
// Executing with lastIndex: 2
// Executing with lastIndex: 5
// Executing with lastIndex: 6
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp-@@species |

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

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

See also
--------

* `RegExp`
* `Symbol.species`


RegExp.prototype.test() - JavaScript

RegExp.prototype.test()
=======================

The **`test()`** method of `RegExp` instances executes a search with this regular expression for a match between a regular expression and a specified string. Returns `true` if there is a match; `false` otherwise.

 JavaScript `RegExp` objects are **stateful** when they have
 the `global` or `sticky` flags
 set (e.g., `/foo/g` or `/foo/y`). They store a
 `lastIndex` from the previous match. Using this
 internally, `test()` can be used to iterate over multiple matches in a string
 of text (with capture groups).

Try it
------

Syntax
------

```js
test(str)
```

### Parameters

`str`

The string against which to match the regular expression. All values are coerced to strings, so omitting it or passing `undefined` causes `test()` to search for the string `"undefined"`, which is rarely what you want.

### Return value

`true` if there is a match between the regular expression and the string
 `str`. Otherwise, `false`.

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

 Use `test()` whenever you want to know whether a pattern is found in a
 string. `test()` returns a boolean, unlike the
 `String.prototype.search()` method (which returns the index of a match, or
 `-1` if not found).

 To get more information (but with slower execution), use the
 `exec()` method. (This is similar to the
 `String.prototype.match()` method.)

 As with `exec()` (or in combination with it), `test()` called
 multiple times on the same global regular expression instance will advance past the
 previous match.

Examples
--------

### Using test()

 Simple example that tests if `"hello"` is contained at the very beginning of
 a string, returning a boolean result.

```js
const str = "hello world!";
const result = /^hello/.test(str);

console.log(result); // true
```

The following example logs a message which depends on the success of the test:

```js
function testInput(re, str) {
  const midstring = re.test(str) ? "contains" : "does not contain";
  console.log(`${str} ${midstring} ${re.source}`);
}
```

### Using test() on a regex with the "global" flag

 When a regex has the global flag set,
 `test()` will advance the `lastIndex` of the regex.
 (`RegExp.prototype.exec()` also advances the `lastIndex` property.)

 Further calls to `test(str)` will resume searching
 `str` starting from `lastIndex`. The
 `lastIndex` property will continue to increase each time `test()`
 returns `true`.

**Note:** As long as `test()` returns `true`,
 `lastIndex` will *not* reset—even when testing a different string!

 When `test()` returns `false`, the calling regex's
 `lastIndex` property will reset to `0`.

The following example demonstrates this behavior:

```js
const regex = /foo/g; // the "global" flag is set

// regex.lastIndex is at 0
regex.test("foo"); // true

// regex.lastIndex is now at 3
regex.test("foo"); // false

// regex.lastIndex is at 0
regex.test("barfoo"); // true

// regex.lastIndex is at 6
regex.test("foobar"); // false

// regex.lastIndex is at 0
regex.test("foobarfoo"); // true

// regex.lastIndex is at 3
regex.test("foobarfoo"); // true

// regex.lastIndex is at 9
regex.test("foobarfoo"); // false

// regex.lastIndex is at 0
// (...and so on)
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp.prototype.test |

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

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

See also
--------

* Regular expressions guide
* `RegExp`


RegExp.prototype.ignoreCase - JavaScript

RegExp.prototype.ignoreCase
===========================

The **`ignoreCase`** accessor property of `RegExp` instances returns whether or not the `i` flag is used with this regular expression.

Try it
------

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

`RegExp.prototype.ignoreCase` has the value `true` if the `i` flag was used; otherwise, `false`. The `i` flag indicates that case should be ignored while attempting a match in a string. Case-insensitive matching is done by mapping both the expected character set and the matched string to the same casing.

If the regex is Unicode-aware, the case mapping happens through *simple case folding* specified in `CaseFolding.txt`. The mapping always maps to a single code point, so it does not map, for example, `ß` (U+00DF LATIN SMALL LETTER SHARP S) to `ss` (which is *full case folding*, not *simple case folding*). It may however map code points outside the Basic Latin block to code points within it — for example, `ſ` (U+017F LATIN SMALL LETTER LONG S) case-folds to `s` (U+0073 LATIN SMALL LETTER S) and `K` (U+212A KELVIN SIGN) case-folds to `k` (U+006B LATIN SMALL LETTER K). Therefore, `ſ` and `K` can be matched by `/[a-z]/ui`.

If the regex is Unicode-unaware, case mapping uses the Unicode Default Case Conversion — the same algorithm used in `String.prototype.toUpperCase()`. For example, `Ω` (U+2126 OHM SIGN) and `Ω` (U+03A9 GREEK CAPITAL LETTER OMEGA) are both mapped by Default Case Conversion to themselves but by simple case folding to `ω` (U+03C9 GREEK SMALL LETTER OMEGA), so `"ω"` is matched by `/[\u2126]/ui` and `/[\u03a9]/ui` but not by `/[\u2126]/i` or `/[\u03a9]/i`. This algorithm prevents code points outside the Basic Latin block to be mapped to code points within it, so `ſ` and `K` mentioned previously are not matched by `/[a-z]/i`.

The set accessor of `ignoreCase` is `undefined`. You cannot change this property directly.

Examples
--------

### Using ignoreCase

```js
const regex = /foo/i;

console.log(regex.ignoreCase); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.ignorecase |

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

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

See also
--------

* `RegExp.prototype.lastIndex`
* `RegExp.prototype.dotAll`
* `RegExp.prototype.global`
* `RegExp.prototype.hasIndices`
* `RegExp.prototype.multiline`
* `RegExp.prototype.source`
* `RegExp.prototype.sticky`
* `RegExp.prototype.unicode`


RegExp.prototype[@@match]() - JavaScript

RegExp.prototype[@@match]()
===========================

The **`[@@match]()`** method of `RegExp` instances specifies how `String.prototype.match()` should behave. In addition, its presence (or absence) can influence whether an object is regarded as a regular expression.

Try it
------

Syntax
------

```js
regexp[Symbol.match](str)
```

### Parameters

`str`

A `String` that is a target of the match.

### Return value

An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or `null` if no matches are found.

* If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included.
* If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties).
Description
-----------

This method is called internally in `String.prototype.match()`.

For example, the following two examples return same result.

```js
"abc".match(/a/);

/a/[Symbol.match]("abc");
```

If the regex is global (with the `g` flag), the regex's `exec()` method will be repeatedly called until `exec()` returns `null`. Otherwise, `exec()` would only be called once and its result becomes the return value of `@@match`.

Because `@@match` would keep calling `exec()` until it returns `null`, and `exec()` would automatically reset the regex's `lastIndex` to 0 when the last match fails, `@@match` would typically not have side effects when it exits. However, when the regex is sticky but not global, `lastIndex` would not be reset. In this case, each call to `match()` may return a different result.

```js
const re = /[abc]/y;
for (let i = 0; i < 5; i++) {
  console.log("abc".match(re), re.lastIndex);
}
// [ 'a' ] 1
// [ 'b' ] 2
// [ 'c' ] 3
// null 0
// [ 'a' ] 1
```

When the regex is sticky and global, it would still perform sticky matches — i.e. it would fail to match any occurrences beyond the `lastIndex`.

```js
console.log("ab-c".match(/[abc]/gy)); // [ 'a', 'b' ]
```

If the current match is an empty string, the `lastIndex` would still be advanced — if the regex is Unicode-aware, it would advance by one Unicode code point; otherwise, it advances by one UTF-16 code unit.

```js
console.log("😄".match(/(?:)/g)); // [ '', '', '' ]
console.log("😄".match(/(?:)/gu)); // [ '', '' ]
```

This method exists for customizing match behavior within `RegExp` subclasses.

In addition, the `@@match` property is used to check whether an object is a regular expression.

Examples
--------

### Direct call

This method can be used in *almost* the same way as `String.prototype.match()`, except the different `this` and the different arguments order.

```js
const re = /[0-9]+/g;
const str = "2016-01-02";
const result = re[Symbol.match](str);
console.log(result); // ["2016", "01", "02"]
```

### Using @@match in subclasses

Subclasses of `RegExp` can override the `[@@match]()` method to modify the default behavior.

```js
class MyRegExp extends RegExp {
  [Symbol.match](str) {
    const result = RegExp.prototype[Symbol.match].call(this, str);
    if (!result) return null;
    return {
      group(n) {
        return result[n];
      },
    };
  }
}

const re = new MyRegExp("([0-9]+)-([0-9]+)-([0-9]+)");
const str = "2016-01-02";
const result = str.match(re); // String.prototype.match calls re[@@match].
console.log(result.group(1)); // 2016
console.log(result.group(2)); // 01
console.log(result.group(3)); // 02
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp.prototype-@@match |

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

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

See also
--------

* Polyfill of `RegExp.prototype[@@match]` in `core-js`
* `String.prototype.match()`
* `RegExp.prototype[@@matchAll]()`
* `RegExp.prototype[@@replace]()`
* `RegExp.prototype[@@search]()`
* `RegExp.prototype[@@split]()`
* `RegExp.prototype.exec()`
* `RegExp.prototype.test()`
* `Symbol.match`


RegExp: lastIndex - JavaScript

RegExp: lastIndex
=================

The **`lastIndex`** data property of a `RegExp` instance specifies the index at which to start the next match.

Try it
------

Value
-----

A non-negative integer.

| Property attributes of `RegExp: lastIndex` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | no |

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

This property is set only if the regular expression instance used the `g` flag to indicate a global search, or the `y` flag to indicate a sticky search. The following rules apply when `exec()` is called on a given input:

* If `lastIndex` is greater than the length of the input, `exec()` will not find a match, and `lastIndex` will be set to 0.
* If `lastIndex` is equal to or less than the length of the input, `exec()` will attempt to match the input starting from `lastIndex`.
    + If `exec()` finds a match, then `lastIndex` will be set to the position of the end of the matched string in the input.
    + If `exec()` does not find a match, then `lastIndex` will be set to 0.

Other regex-related methods, such as `RegExp.prototype.test()`, `String.prototype.match()`, `String.prototype.replace()`, etc., call `exec()` under the hood, so they have different effects on `lastIndex`. See their respective pages for details.

Examples
--------

### Using lastIndex

Consider the following sequence of statements:

```js
const re = /(hi)?/g;
```

Matches the empty string.

```js
console.log(re.exec("hi"));
console.log(re.lastIndex);
```

Returns `["hi", "hi"]` with `lastIndex` equal to 2.

```js
console.log(re.exec("hi"));
console.log(re.lastIndex);
```

Returns `["", undefined]`, an empty array whose zeroth element is the match string. In this case, the empty string because `lastIndex` was 2 (and still is 2) and `hi` has length 2.

### Using lastIndex with sticky regexes

The `lastIndex` property is writable. You can set it to make the regex start its next search at a given index.

The `y` flag almost always requires setting `lastIndex`. It always matches strictly at `lastIndex` and does not attempt any later positions. This is usually useful for writing parsers, when you want to match tokens only at the current position.

```js
const stringPattern = /"[^"]\*"/y;
const input = `const message = "Hello world";`;

stringPattern.lastIndex = 6;
console.log(stringPattern.exec(input)); // null

stringPattern.lastIndex = 16;
console.log(stringPattern.exec(input)); // ['"Hello world"']
```

### Rewinding lastIndex

The `g` flag also benefits from setting `lastIndex`. One common use case is when the string is modified in the middle of a global search. In this case, we may miss a particular match if the string is shortened. We can avoid this by rewinding `lastIndex`.

```js
const mdLinkPattern = /\[[^[\]]+\]\((?<link>[^()\s]+)\)/dg;

function resolveMDLink(line) {
  let match;
  let modifiedLine = line;
  while ((match = mdLinkPattern.exec(modifiedLine))) {
    const originalLink = match.groups.link;
    const resolvedLink = originalLink.replaceAll(/^files|\/index\.md$/g, "");
    modifiedLine =
      modifiedLine.slice(0, match.indices.groups.link[0]) +
      resolvedLink +
      modifiedLine.slice(match.indices.groups.link[1]);
    // Rewind the pattern to the end of the resolved link
    mdLinkPattern.lastIndex += resolvedLink.length - originalLink.length;
  }
  return modifiedLine;
}

console.log(
  resolveMDLink(
    "[`lastIndex`](files/en-us/web/javascript/reference/global\_objects/regexp/lastindex/index.md)",
  ),
); // [`lastIndex`](/en-us/web/javascript/reference/global\_objects/regexp/lastindex)
console.log(
  resolveMDLink(
    "[`ServiceWorker`](files/en-us/web/api/serviceworker/index.md) and [`SharedWorker`](files/en-us/web/api/sharedworker/index.md)",
  ),
); // [`ServiceWorker`](/en-us/web/api/serviceworker) and [`SharedWorker`](/en-us/web/api/sharedworker)
```

Try deleting the `mdLinkPattern.lastIndex += resolvedLink.length - originalLink.length` line and running the second example. You will find that the second link is not replaced correctly, because the `lastIndex` is already past the link's index after the string is shortened.

**Warning:** This example is for demonstration only. To deal with Markdown, you should probably use a parsing library instead of regex.

### Optimizing searching

You can optimize searching by setting `lastIndex` to a point where previous possible occurrences can be ignored. For example, instead of this:

```js
const stringPattern = /"[^"]\*"/g;
const input = `const message = "Hello " + "world";`;

// Pretend we've already dealt with the previous parts of the string
let offset = 26;
const remainingInput = input.slice(offset);
const nextString = stringPattern.exec(remainingInput);
console.log(nextString[0]); // "world"
offset += nextString.index + nextString.length;
```

Consider this:

```js
stringPattern.lastIndex = offset;
const nextString = stringPattern.exec(remainingInput);
console.log(nextString[0]); // "world"
offset = stringPattern.lastIndex;
```

This is potentially more performant because we avoid string slicing.

### Avoiding side effects

The side effects caused by `exec()` can be confusing, especially if the input is different for each `exec()`.

```js
const re = /foo/g;
console.log(re.test("foo bar")); // true
console.log(re.test("foo baz")); // false, because lastIndex is non-zero
```

This is even more confusing when you are hand-modifying `lastIndex`. To contain the side effects, remember to reset `lastIndex` after each input is completely processed.

```js
const re = /foo/g;
console.log(re.test("foo bar")); // true
re.lastIndex = 0;
console.log(re.test("foo baz")); // true
```

With some abstraction, you can require `lastIndex` to be set to a particular value before each `exec()` call.

```js
function createMatcher(pattern) {
  // Create a copy, so that the original regex is never updated
  const regex = new RegExp(pattern, "g");
  return (input, offset) => {
    regex.lastIndex = offset;
    return regex.exec(input);
  };
}

const matchFoo = createMatcher(/foo/);
console.log(matchFoo("foo bar", 0)[0]); // "foo"
console.log(matchFoo("foo baz", 0)[0]); // "foo"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-properties-of-regexp-instances |

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

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

See also
--------

* `RegExp.prototype.dotAll`
* `RegExp.prototype.global`
* `RegExp.prototype.hasIndices`
* `RegExp.prototype.ignoreCase`
* `RegExp.prototype.multiline`
* `RegExp.prototype.source`
* `RegExp.prototype.sticky`
* `RegExp.prototype.unicode`


RegExp.$1, …, RegExp.$9 - JavaScript

RegExp.$1, …, RegExp.$9
=======================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The **`RegExp.$1, …, RegExp.$9`** static accessor properties return parenthesized substring matches.

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

Because `$1`–`$9` are static properties of `RegExp`, you always use them as `RegExp.$1`, `RegExp.$2`, etc., rather than as properties of a `RegExp` object you created.

The values of `$1, …, $9` update whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, or if the last match does not have the corresponding capturing group, the respective property is an empty string. The set accessor of each property is `undefined`, so you cannot change the properties directly.

The number of possible parenthesized substrings is unlimited, but the `RegExp` object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.

`$1, …, $9` can also be used in the replacement string of `String.prototype.replace()`, but that's unrelated to the `RegExp.$n` legacy properties.

Examples
--------

### Using $n with RegExp.prototype.test()

The following script uses the `RegExp.prototype.test()` method to grab a number in a generic string.

```js
const str = "Test 24";
const number = /(\d+)/.test(str) ? RegExp.$1 : "0";
number; // "24"
```

Please note that any operation involving the usage of other regular expressions between a `re.test(str)` call and the `RegExp.$n` property, might have side effects, so that accessing these special properties should be done instantly, otherwise the result might be unexpected.

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

| Specification |
| --- |
| Legacy RegExp features # additional-properties-of-the-regexp-constructor |

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

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

See also
--------

* `RegExp.input ($_)`
* `RegExp.lastMatch ($&)`
* `RegExp.lastParen ($+)`
* `RegExp.leftContext ($`)`
* `RegExp.rightContext ($')`


RegExp.prototype.hasIndices - JavaScript

RegExp.prototype.hasIndices
===========================

The **`hasIndices`** accessor property of `RegExp` instances returns whether or not the `d` flag is used with this regular expression.

Try it
------

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

`RegExp.prototype.hasIndices` has the value `true` if the `d` flag was used; otherwise, `false`. The `d` flag indicates that the result of a regular expression match should contain the start and end indices of the substrings of each capture group. It does not change the regex's interpretation or matching behavior in any way, but only provides additional information in the matching result.

This flag primarily affects the return value of `exec()`. If the `d` flag is present, the array returned by `exec()` has an additional `indices` property as described in the `exec()` method's return value. Because all other regex-related methods (such as `String.prototype.match()`) call `exec()` internally, they will also return the indices if the regex has the `d` flag.

The set accessor of `hasIndices` is `undefined`. You cannot change this property directly.

Examples
--------

There's a more detailed usage example at Groups and backreferences > Using groups and match indices.

### Using hasIndices

```js
const str1 = "foo bar foo";

const regex1 = /foo/dg;

console.log(regex1.hasIndices); // true

console.log(regex1.exec(str1).indices[0]); // [0, 3]
console.log(regex1.exec(str1).indices[0]); // [8, 11]

const str2 = "foo bar foo";

const regex2 = /foo/;

console.log(regex2.hasIndices); // false

console.log(regex2.exec(str2).indices); // undefined
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.hasIndices |

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

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

See also
--------

* `RegExp.prototype.lastIndex`
* `RegExp.prototype.exec()`
* `RegExp.prototype.dotAll`
* `RegExp.prototype.global`
* `RegExp.prototype.ignoreCase`
* `RegExp.prototype.multiline`
* `RegExp.prototype.source`
* `RegExp.prototype.sticky`
* `RegExp.prototype.unicode`


RegExp.prototype[@@matchAll]() - JavaScript

RegExp.prototype[@@matchAll]()
==============================

The **`[@@matchAll]()`** method of `RegExp` instances specifies how `String.prototype.matchAll` should behave.

Try it
------

Syntax
------

```js
regexp[Symbol.matchAll](str)
```

### Parameters

`str`

A `String` that is a target of the match.

### Return value

An iterable iterator object (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`.

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

This method is called internally in `String.prototype.matchAll()`. For example, the following two examples return the same result.

```js
"abc".matchAll(/a/g);

/a/g[Symbol.matchAll]("abc");
```

Like `@@split`, `@@matchAll` starts by using `@@species` to construct a new regex, thus avoiding mutating the original regexp in any way. `lastIndex` starts as the original regex's value.

```js
const regexp = /[a-c]/g;
regexp.lastIndex = 1;
const str = "abc";
Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);
// [ "1 b", "1 c" ]
```

The validation that the input is a global regex happens in `String.prototype.matchAll()`. `@@matchAll` does not validate the input. If the regex is not global, the returned iterator yields the `exec()` result once and then returns `undefined`. If the regexp is global, each time the returned iterator's `next()` method is called, the regex's `exec()` is called and the result is yielded.

When the regex is sticky and global, it will still perform sticky matches — i.e. it will not match any occurrences beyond the `lastIndex`.

```js
console.log(Array.from("ab-c".matchAll(/[abc]/gy)));
// [ [ "a" ], [ "b" ] ]
```

If the current match is an empty string, the `lastIndex` will still be advanced. If the regex has the `u` flag, it advances by one Unicode code point; otherwise, it advances by one UTF-16 code point.

```js
console.log(Array.from("😄".matchAll(/(?:)/g)));
// [ [ "" ], [ "" ], [ "" ] ]

console.log(Array.from("😄".matchAll(/(?:)/gu)));
// [ [ "" ], [ "" ] ]
```

This method exists for customizing the behavior of `matchAll()` in `RegExp` subclasses.

Examples
--------

### Direct call

This method can be used in almost the same way as `String.prototype.matchAll()`, except for the different value of `this` and the different order of arguments.

```js
const re = /[0-9]+/g;
const str = "2016-01-02";
const result = re[Symbol.matchAll](str);

console.log(Array.from(result, (x) => x[0]));
// [ "2016", "01", "02" ]
```

### Using @@matchAll in subclasses

Subclasses of `RegExp` can override the `[@@matchAll]()` method to modify the default behavior.

For example, to return an `Array` instead of an iterator:

```js
class MyRegExp extends RegExp {
  [Symbol.matchAll](str) {
    const result = RegExp.prototype[Symbol.matchAll].call(this, str);
    return result ? Array.from(result) : null;
  }
}

const re = new MyRegExp("([0-9]+)-([0-9]+)-([0-9]+)", "g");
const str = "2016-01-02|2019-03-07";
const result = str.matchAll(re);

console.log(result[0]);
// [ "2016-01-02", "2016", "01", "02" ]

console.log(result[1]);
// [ "2019-03-07", "2019", "03", "07" ]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp-prototype-matchall |

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

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

See also
--------

* Polyfill of `RegExp.prototype[@@matchAll]` in `core-js`
* `String.prototype.matchAll()`
* `RegExp.prototype[@@match]()`
* `RegExp.prototype[@@replace]()`
* `RegExp.prototype[@@search]()`
* `RegExp.prototype[@@split]()`
* `Symbol.matchAll`


RegExp.lastMatch ($&) - JavaScript

RegExp.lastMatch ($&)
=====================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The **`RegExp.lastMatch`** static accessor property returns the last matched substring. `RegExp["$&"]` is an alias for this property.

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

Because `lastMatch` is a static property of `RegExp`, you always use it as `RegExp.lastMatch` or `RegExp["$&"]`, rather than as a property of a `RegExp` object you created.

The value of `lastMatch` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `lastMatch` is an empty string. The set accessor of `lastMatch` is `undefined`, so you cannot change this property directly.

You cannot use the shorthand alias with the dot property accessor (`RegExp.$&`), because `&` is not a valid identifier part, so this causes a `SyntaxError`. Use the bracket notation instead.

`$&` can also be used in the replacement string of `String.prototype.replace()`, but that's unrelated to the `RegExp["$&"]` legacy property.

Examples
--------

### Using lastMatch and $&

```js
const re = /hi/g;
re.test("hi there!");
RegExp.lastMatch; // "hi"
RegExp["$&"]; // "hi"
```

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

| Specification |
| --- |
| Legacy RegExp features # additional-properties-of-the-regexp-constructor |

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

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

See also
--------

* `RegExp.input ($_)`
* `RegExp.lastParen ($+)`
* `RegExp.leftContext ($`)`
* `RegExp.rightContext ($')`
* `RegExp.$1, …, RegExp.$9`


RegExp.prototype.unicode - JavaScript

RegExp.prototype.unicode
========================

The **`unicode`** accessor property of `RegExp` instances returns whether or not the `u` flag is used with this regular expression.

Try it
------

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

`RegExp.prototype.unicode` has the value `true` if the `u` flag was used; otherwise, `false`. The `u` flag enables various Unicode-related features. With the "u" flag:

* Any Unicode code point escapes (`\u{xxxx}`, `\p{UnicodePropertyValue}`) will be interpreted as such instead of identity escapes. For example `/\u{61}/u` matches `"a"`, but `/\u{61}/` (without `u` flag) matches `"u".repeat(61)`, where the `\u` is equivalent to a single `u`.
* Surrogate pairs will be interpreted as whole characters instead of two separate characters. For example, `/[😄]/u` would only match `"😄"` but not `"\ud83d"`.
* When `lastIndex` is automatically advanced (such as when calling `exec()`), unicode regexes advance by Unicode code points instead of UTF-16 code units.

There are other changes to the parsing behavior that prevent possible syntax mistakes (which are analogous to strict mode for regex syntax). These syntaxes are all deprecated and only kept for web compatibility, and you should not rely on them.

The set accessor of `unicode` is `undefined`. You cannot change this property directly.

### Unicode-aware mode

When we refer to *Unicode-aware mode*, we mean the regex has either the `u` or the `v` flag, in which case the regex enables Unicode-related features (such as Unicode character class escape) and has much stricter syntax rules. Because `u` and `v` interpret the same regex in incompatible ways, using both flags results in a `SyntaxError`.

Similarly, a regex is *Unicode-unaware* if it has neither the `u` nor the `v` flag. In this case, the regex is interpreted as a sequence of UTF-16 code units, and there are many legacy syntaxes that do not become syntax errors.

Examples
--------

### Using the unicode property

```js
const regex = /\u{61}/u;

console.log(regex.unicode); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.unicode |

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

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

See also
--------

* `RegExp.prototype.lastIndex`
* `RegExp.prototype.dotAll`
* `RegExp.prototype.global`
* `RegExp.prototype.hasIndices`
* `RegExp.prototype.ignoreCase`
* `RegExp.prototype.multiline`
* `RegExp.prototype.source`
* `RegExp.prototype.sticky`


RegExp.prototype.flags - JavaScript

RegExp.prototype.flags
======================

The **`flags`** accessor property of `RegExp` instances returns the flags of this regular expression.

Try it
------

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

`RegExp.prototype.flags` has a string as its value. Flags in the `flags` property are sorted alphabetically (from left to right, e.g. `"dgimsuvy"`). It actually invokes the other flag accessors (`hasIndices`, `global`, etc.) one-by-one and concatenates the results.

All built-in functions read the `flags` property instead of reading individual flag accessors.

The set accessor of `flags` is `undefined`. You cannot change this property directly.

Examples
--------

### Using flags

```js
/foo/ig.flags; // "gi"
/bar/myu.flags; // "muy"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.flags |

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

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

See also
--------

* Polyfill of `RegExp.prototype.flags` in `core-js`
* Advanced searching with flags in the Regular expressions guide
* `RegExp.prototype.source`


RegExp.prototype.exec() - JavaScript

RegExp.prototype.exec()
=======================

The **`exec()`** method of `RegExp` instances executes a search with this regular expression for a match in a specified string and returns a result array, or `null`.

Try it
------

Syntax
------

```js
exec(str)
```

### Parameters

`str`

The string against which to match the regular expression. All values are coerced to strings, so omitting it or passing `undefined` causes `exec()` to search for the string `"undefined"`, which is rarely what you want.

### Return value

If the match fails, the `exec()` method returns `null`, and sets the regex's `lastIndex` to `0`.

If the match succeeds, the `exec()` method returns an array and updates the `lastIndex` property of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing group of the matched text. The array also has the following additional properties:

`index`

The 0-based index of the match in the string.

`input`

The original string that was matched against.

`groups`

A `null`-prototype object of named capturing groups, whose keys are the names, and values are the capturing groups, or `undefined` if no named capturing groups were defined. See capturing groups for more information.

`indices` Optional

This property is only present when the `d` flag is set. It is an array where each entry represents the bounds of a substring match. The index of each element in this array corresponds to the index of the respective substring match in the array returned by `exec()`. In other words, the first `indices` entry represents the entire match, the second `indices` entry represents the first capturing group, etc. Each entry itself is a two-element array, where the first number represents the match's start index, and the second number, its end index.

The `indices` array additionally has a `groups` property, which holds a `null`-prototype object of all named capturing groups. The keys are the names of the capturing groups, and each value is a two-element array, with the first number being the start index, and the second number being the end index of the capturing group. If the regular expression doesn't contain any named capturing groups, `groups` is `undefined`.

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

JavaScript `RegExp` objects are *stateful* when they have the global or sticky flags set (e.g. `/foo/g` or `/foo/y`). They store a `lastIndex` from the previous match. Using this internally, `exec()` can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with `String.prototype.match()`.

When using `exec()`, the global flag has no effect when the sticky flag is set — the match is always sticky.

`exec()` is the primitive method of regexps. Many other regexp methods call `exec()` internally — including those called by string methods, like `@@replace`. While `exec()` itself is powerful (and is the most efficient), it often does not convey the intent most clearly.

* If you only care whether the regex matches a string, but not what is actually being matched, use `RegExp.prototype.test()` instead.
* If you are finding all occurrences of a global regex and you don't care about information like capturing groups, use `String.prototype.match()` instead. In addition, `String.prototype.matchAll()` helps to simplify matching multiple parts of a string (with capture groups) by allowing you to iterate over the matches.
* If you are executing a match to find its index position in the string, use the `String.prototype.search()` method instead.
Examples
--------

### Using exec()

Consider the following example:

```js
// Match "quick brown" followed by "jumps", ignoring characters in between
// Remember "brown" and "jumps"
// Ignore case
const re = /quick\s(?<color>brown).+?(jumps)/dgi;
const result = re.exec("The Quick Brown Fox Jumps Over The Lazy Dog");
```

The following table shows the state of `result` after running this script:

| Property | Value |
| --- | --- |
| `[0]` | `"Quick Brown Fox Jumps"` |
| `[1]` | `"Brown"` |
| `[2]` | `"Jumps"` |
| `index` | `4` |
| `indices` | `[[4, 25], [10, 15], [20, 25]]``groups: { color: [10, 15 ]}` |
| `input` | `"The Quick Brown Fox Jumps Over The Lazy Dog"` |
| `groups` | `{ color: "brown" }` |

In addition, `re.lastIndex` will be set to `25`, due to this regex being global.

### Finding successive matches

If your regular expression uses the `g` flag, you can use the `exec()` method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of `str` specified by the regular expression's `lastIndex` property (`test()` will also advance the `lastIndex` property). Note that the `lastIndex` property will not be reset when searching a different string, it will start its search at its existing `lastIndex`.

For example, assume you have this script:

```js
const myRe = /ab\*/g;
const str = "abbcdefabh";
let myArray;
while ((myArray = myRe.exec(str)) !== null) {
  let msg = `Found ${myArray[0]}. `;
  msg += `Next match starts at ${myRe.lastIndex}`;
  console.log(msg);
}
```

This script displays the following text:
```

Found abb. Next match starts at 3
Found ab. Next match starts at 9
```

**Warning:** There are many pitfalls that can lead to this becoming an infinite loop!

* Do *not* place the regular expression literal (or `RegExp` constructor) within the `while` condition — it will recreate the regex for every iteration and reset `lastIndex`.
* Be sure that the global (`g`) flag is set, or `lastIndex` will never be advanced.
* If the regex may match zero-length characters (e.g. `/^/gm`), increase its `lastIndex` manually each time to avoid being stuck in the same place.

You can usually replace this kind of code with `String.prototype.matchAll()` to make it less error-prone.

### Using exec() with RegExp literals

 You can also use `exec()` without creating a `RegExp` object
 explicitly:

```js
const matches = /(hello \S+)/.exec("This is a hello world!");
console.log(matches[1]);
```

This will log a message containing `'hello world!'`.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-regexp.prototype.exec |

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

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

See also
--------

* Regular expressions guide
* `RegExp`


RegExp.prototype.multiline - JavaScript

RegExp.prototype.multiline
==========================

The **`multiline`** accessor property of `RegExp` instances returns whether or not the `m` flag is used with this regular expression.

Try it
------

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

`RegExp.prototype.multiline` has the value `true` if the `m` flag was used; otherwise, `false`. The `m` flag indicates that a multiline input string should be treated as multiple lines. For example, if `m` is used, `^` and `$` change from matching at only the start or end of the entire string to the start or end of any line within the string.

The set accessor of `multiline` is `undefined`. You cannot change this property directly.

Examples
--------

### Using multiline

```js
const regex = /foo/m;

console.log(regex.multiline); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-regexp.prototype.multiline |

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

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

See also
--------

* `RegExp.prototype.lastIndex`
* `RegExp.prototype.dotAll`
* `RegExp.prototype.global`
* `RegExp.prototype.hasIndices`
* `RegExp.prototype.ignoreCase`
* `RegExp.prototype.source`
* `RegExp.prototype.sticky`
* `RegExp.prototype.unicode`


Float64Array() constructor - JavaScript

Float64Array() constructor
==========================

The **`Float64Array()`** constructor creates `Float64Array` objects. The contents are initialized to `0`.

Syntax
------

```js
new Float64Array()
new Float64Array(length)
new Float64Array(typedArray)
new Float64Array(object)

new Float64Array(buffer)
new Float64Array(buffer, byteOffset)
new Float64Array(buffer, byteOffset, length)
```

**Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

See `TypedArray`.

### Exceptions

See `TypedArray`.

Examples
--------

### Different ways to create a Float64Array

```js
// From a length
const float64 = new Float64Array(2);
float64[0] = 42;
console.log(float64[0]); // 42
console.log(float64.length); // 2
console.log(float64.BYTES\_PER\_ELEMENT); // 8

// From an array
const x = new Float64Array([21, 31]);
console.log(x[1]); // 31

// From another TypedArray
const y = new Float64Array(x);
console.log(y[0]); // 21

// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new Float64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8

// From an iterable
const iterable = (function\* () {
  yield\* [1, 2, 3];
})();
const float64FromIterable = new Float64Array(iterable);
console.log(float64FromIterable);
// Float64Array [1, 2, 3]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-typedarray-constructors |

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

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

See also
--------

* Polyfill of `Float64Array` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`


Iterator.prototype.toArray() - JavaScript

Iterator.prototype.toArray()
============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`toArray()`** method of `Iterator` instances creates a new `Array` instance populated with the elements yielded from the iterator.

Syntax
------

```js
toArray()
```

### Parameters

None.

### Return value

A new `Array` instance containing the elements from the iterator in the order they were produced.

Examples
--------

### Using toArray()

`iterator.toArray()` is equivalent to `Array.from(iterator)` and `[...iterator]`, except that it's easier to chain when multiple iterator helper methods are involved. The following example creates an iterator that yields terms in the Fibonacci sequence, takes the first 10 terms, filters out the odd numbers, and converts the result to an array:

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const array = fibonacci()
  .take(10)
  .filter((x) => x % 2 === 0)
  .toArray();

console.log(array); // [2, 8, 34]
```

Note that it's a good idea to call `toArray()` as a last step of your processing. For example, `fibonacci().take(10).toArray().filter(...)` is less efficient, because iterator helpers are lazy and avoids creating a temporary array.

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.toarray |

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

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

See also
--------

* Polyfill of `Iterator.prototype.toArray` in `core-js`
* `Iterator`
* `Array.from()`


Iterator.prototype[@@iterator]() - JavaScript

Iterator.prototype[@@iterator]()
================================

The **`[@@iterator]()`** method of `Iterator` instances implements the iterable protocol and allows built-in iterators to be consumed by most syntaxes expecting iterables, such as the spread syntax and `for...of` loops. It returns the value of `this`, which is the iterator object itself.

Syntax
------

```js
iterator[Symbol.iterator]()
```

### Parameters

None.

### Return value

The value of `this`, which is the iterator object itself.

Examples
--------

### Iteration using for...of loop

Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes built-in iterators iterable, and iterating syntaxes like the `for...of` loop automatically call this method to obtain the iterator to loop over.

```js
const arrIterator = [1, 2, 3].values();
for (const value of arrIterator) {
  console.log(value);
}
// Logs: 1, 2, 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%iteratorprototype%-@@iterator |

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

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

See also
--------

* `Iterator`
* `Symbol.iterator`
* Iteration protocols


Iterator.prototype.filter() - JavaScript

Iterator.prototype.filter()
===========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`filter()`** method of `Iterator` instances returns a new iterator helper that yields only those elements of the iterator for which the provided callback function returns `true`.

Syntax
------

```js
filter(callbackFn)
```

### Parameters

`callbackFn`

A function to execute for each element produced by the iterator. It should return a truthy value to make the element yielded by the iterator helper, and a falsy value otherwise. The function is called with the following arguments:

`element`

The current element being processed.

`index`

The index of the current element being processed.

### Return value

A new iterator helper. Each time the iterator helper's `next()` method is called, it returns the next element in the iterator for which the callback function returns `true`. When the underlying iterator is completed, the iterator helper is also completed (the `next()` method produces `{ value: undefined, done: true }`).

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

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `filter()` allows you to iterate over only those elements that satisfy a given condition.

Examples
--------

### Using filter()

The following example creates an iterator that yields terms in the Fibonacci sequence, and then reads the first few terms that are even:

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const seq = fibonacci().filter((x) => x % 2 === 0);
console.log(seq.next().value); // 2
console.log(seq.next().value); // 8
console.log(seq.next().value); // 34
```

### Using filter() with a for...of loop

`filter()` is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a `for...of` loop:

```js
for (const n of fibonacci().filter((x) => x % 2 === 0)) {
  console.log(n);
  if (n > 30) {
    break;
  }
}

// Logs:
// 2
// 8
// 34
```

This is equivalent to:

```js
for (const n of fibonacci()) {
  if (n % 2 !== 0) {
    continue;
  }
  console.log(n);
  if (n > 30) {
    break;
  }
}
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.filter |

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

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

See also
--------

* Polyfill of `Iterator.prototype.filter` in `core-js`
* `Iterator`
* `Iterator.prototype.forEach()`
* `Iterator.prototype.every()`
* `Iterator.prototype.map()`
* `Iterator.prototype.some()`
* `Iterator.prototype.reduce()`
* `Array.prototype.filter()`