Iterators and generators - JavaScript

Iterators and generators
========================

* « Previous
* Next »

Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of `for...of` loops.

For details, see also:

* Iteration protocols
* `for...of`
* `function*` and `Generator`
* `yield` and `yield*`
Iterators
---------

In JavaScript an **iterator** is an object which defines a sequence and potentially a return value upon its termination.

Specifically, an iterator is any object which implements the Iterator protocol by having a `next()` method that returns an object with two properties:

`value`

The next value in the iteration sequence.

`done`

This is `true` if the last value in the sequence has already been consumed. If `value` is present alongside `done`, it is the iterator's return value.

Once created, an iterator object can be iterated explicitly by repeatedly calling `next()`. Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to `next()` should continue to return `{done: true}`.

The most common iterator in JavaScript is the Array iterator, which returns each value in the associated array in sequence.

While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary. Because of this, iterators can express sequences of unlimited size, such as the range of integers between `0` and `Infinity`.

Here is an example which can do just that. It allows creation of a simple range iterator which defines a sequence of integers from `start` (inclusive) to `end` (exclusive) spaced `step` apart. Its final return value is the size of the sequence it created, tracked by the variable `iterationCount`.

```js
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
  let nextIndex = start;
  let iterationCount = 0;

  const rangeIterator = {
    next() {
      let result;
      if (nextIndex < end) {
        result = { value: nextIndex, done: false };
        nextIndex += step;
        iterationCount++;
        return result;
      }
      return { value: iterationCount, done: true };
    },
  };
  return rangeIterator;
}
```

Using the iterator then looks like this:

```js
const iter = makeRangeIterator(1, 10, 2);

let result = iter.next();
while (!result.done) {
  console.log(result.value); // 1 3 5 7 9
  result = iter.next();
}

console.log("Iterated over sequence of size:", result.value); // [5 numbers returned, that took interval in between: 0 to 10]
```

**Note:** It is not possible to know reflectively whether a particular object is an iterator. If you need to do this, use Iterables.

Generator functions
-------------------

While custom iterators are a useful tool, their creation requires careful programming due to the need to explicitly maintain their internal state. **Generator functions** provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. Generator functions are written using the `function*` syntax.

When called, generator functions do not initially execute their code. Instead, they return a special type of iterator, called a **Generator**. When a value is consumed by calling the generator's `next` method, the Generator function executes until it encounters the `yield` keyword.

The function can be called as many times as desired, and returns a new Generator each time. Each Generator may only be iterated once.

We can now adapt the example from above. The behavior of this code is identical, but the implementation is much easier to write and read.

```js
function\* makeRangeIterator(start = 0, end = Infinity, step = 1) {
  let iterationCount = 0;
  for (let i = start; i < end; i += step) {
    iterationCount++;
    yield i;
  }
  return iterationCount;
}
```

Iterables
---------

An object is **iterable** if it defines its iteration behavior, such as what values are looped over in a `for...of` construct. Some built-in types, such as `Array` or `Map`, have a default iteration behavior, while other types (such as `Object`) do not.

In order to be **iterable**, an object must implement the **@@iterator** method. This means that the object (or one of the objects up its prototype chain) must have a property with a `Symbol.iterator` key.

It may be possible to iterate over an iterable more than once, or only once. It is up to the programmer to know which is the case.

Iterables which can iterate only once (such as Generators) customarily return `this` from their **@@iterator** method, whereas iterables which can be iterated many times must return a new iterator on each invocation of **@@iterator**.

```js
function\* makeIterator() {
  yield 1;
  yield 2;
}

const iter = makeIterator();

for (const itItem of iter) {
  console.log(itItem);
}

console.log(iter[Symbol.iterator]() === iter); // true

// This example show us generator(iterator) is iterable object,
// which has the @@iterator method return the `iter` (itself),
// and consequently, the it object can iterate only \_once\_.

// If we change the @@iterator method of `iter` to a function/generator
// which returns a new iterator/generator object, `iter`
// can iterate many times

iter[Symbol.iterator] = function\* () {
  yield 2;
  yield 1;
};
```

### User-defined iterables

You can make your own iterables like this:

```js
const myIterable = {
  \*[Symbol.iterator]() {
    yield 1;
    yield 2;
    yield 3;
  },
};
```

User-defined iterables can be used in `for...of` loops or the spread syntax as usual.

```js
for (const value of myIterable) {
  console.log(value);
}
// 1
// 2
// 3

[...myIterable]; // [1, 2, 3]
```

### Built-in iterables

`String`, `Array`, `TypedArray`, `Map` and `Set` are all built-in iterables, because their prototype objects all have a `Symbol.iterator` method.

### Syntaxes expecting iterables

Some statements and expressions expect iterables. For example: the `for...of` loops, spread syntax, `yield*`, and destructuring syntax.

```js
for (const value of ["a", "b", "c"]) {
  console.log(value);
}
// "a"
// "b"
// "c"

[..."abc"];
// ["a", "b", "c"]

function\* gen() {
  yield\* ["a", "b", "c"];
}

gen().next();
// { value: "a", done: false }

[a, b, c] = new Set(["a", "b", "c"]);
a;
// "a"
```

Advanced generators
-------------------

Generators compute their `yield`ed values *on demand*, which allows them to efficiently represent sequences that are expensive to compute (or even infinite sequences, as demonstrated above).

The `next()` method also accepts a value, which can be used to modify the internal state of the generator. A value passed to `next()` will be received by `yield` .

**Note:** A value passed to the *first* invocation of `next()` is always ignored.

Here is the fibonacci generator using `next(x)` to restart the sequence:

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

const sequence = fibonacci();
console.log(sequence.next().value); // 0
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
console.log(sequence.next().value); // 3
console.log(sequence.next().value); // 5
console.log(sequence.next().value); // 8
console.log(sequence.next(true).value); // 0
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
```

You can force a generator to throw an exception by calling its `throw()` method and passing the exception value it should throw. This exception will be thrown from the current suspended context of the generator, as if the `yield` that is currently suspended were instead a `throw value` statement.

If the exception is not caught from within the generator, it will propagate up through the call to `throw()`, and subsequent calls to `next()` will result in the `done` property being `true`.

Generators have a `return()` method that returns the given value and finishes the generator itself.

* « Previous
* Next »


Regular expressions - JavaScript

Regular expressions
===================

* « Previous
* Next »

 Regular expressions are patterns used to match character combinations in strings.
 In JavaScript, regular expressions are also objects. These patterns are used with the `exec()` and `test()` methods of `RegExp`, and with the `match()`, `matchAll()`, `replace()`, `replaceAll()`, `search()`, and `split()` methods of `String`.
 This chapter describes JavaScript regular expressions.

Creating a regular expression
-----------------------------

You construct a regular expression in one of two ways:

* Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:

```js
const re = /ab+c/;
```

Regular expression literals provide compilation of the regular expression when the script is loaded.
 If the regular expression remains constant, using this can improve performance.
* Or calling the constructor function of the `RegExp` object, as follows:

```js
const re = new RegExp("ab+c");
```

Using the constructor function provides runtime compilation of the regular expression.
 Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
Writing a regular expression pattern
------------------------------------

 A regular expression pattern is composed of simple characters, such as `/abc/`, or a combination of simple and special characters, such as `/ab*c/` or `/Chapter (\d+)\.\d*/`.
 The last example includes parentheses, which are used as a memory device.
 The match made with this part of the pattern is remembered for later use, as described in Using groups.

**Note:** If you are already familiar with the forms of a regular expression, you may also read the cheat sheet for a quick lookup for a specific pattern/construct.

### Using simple patterns

 Simple patterns are constructed of characters for which you want to find a direct match. For example, the pattern `/abc/` matches character combinations in strings only when the exact sequence `"abc"` occurs (all characters together and in that order).
 Such a match would succeed in the strings `"Hi, do you know your abc's?"` and `"The latest airplane designs evolved from slabcraft."`.
 In both cases the match is with the substring `"abc"`.
 There is no match in the string `"Grab crab"` because while it contains the substring `"ab c"`, it does not contain the exact substring `"abc"`.

### Using special characters

 When the search for a match requires something more than a direct match, such as finding one or more b's, or finding white space, you can include special characters in the pattern.
 For example, to match *a single `"a"` followed by zero or more `"b"`s followed by `"c"`*, you'd use the pattern `/ab*c/`: the `*` after `"b"` means "0 or more occurrences of the preceding item."
 In the string `"cbbabbbbcdebc"`, this pattern will match the substring `"abbbbc"`.

The following pages provide lists of the different special characters that fit into each category, along with descriptions and examples.

Assertions guide

Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).

Character classes guide

Distinguish different types of characters. For example, distinguishing between letters and digits.

Groups and backreferences guide

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.

Quantifiers guide

Indicate numbers of characters or expressions to match.

If you want to look at all the special characters that can be used in regular expressions in a single table, see the following:

Special characters in regular expressions.| Characters / constructs | Corresponding article |
| --- | --- |
| `[xyz]`, `[^xyz]`, `.`,
 `\d`, `\D`, `\w`, `\W`,
 `\s`, `\S`, `\t`, `\r`,
 `\n`, `\v`, `\f`, `[\b]`,
 `\0`, `\c*X*`, `\x*hh*`,
 `\u*hhhh*`, `\u*{hhhh}*`,
 `*x*|*y*` | Character classes |
| `^`, `$`, `\b`, `\B`,
 `x(?=y)`, `x(?!y)`, `(?<=y)x`,
 `(?<!y)x` | Assertions |
| `(*x*)`, `(?<Name>x)`, `(?:*x*)`,
 `\*n*`, `\k<Name>` | Groups and backreferences |
| `*x**`, `*x*+`, `*x*?`,
 `*x*{*n*}`, `*x*{*n*,}`,
 `*x*{*n*,*m*}` | Quantifiers |

**Note:** A larger cheat sheet is also available (only aggregating parts of those individual articles).

### Escaping

 If you need to use any of the special characters literally (actually searching for a `"*"`, for instance), you must escape it by putting a backslash in front of it.
 For instance, to search for `"a"` followed by `"*"` followed by `"b"`, you'd use `/a\*b/` — the backslash "escapes" the `"*"`, making it literal instead of special.

 Similarly, if you're writing a regular expression literal and need to match a slash ("/"), you need to escape that (otherwise, it terminates the pattern).
 For instance, to search for the string "/example/" followed by one or more alphabetic characters, you'd use `/\/example\/[a-z]+/i`—the backslashes before each slash make them literal.

 To match a literal backslash, you need to escape the backslash.
 For instance, to match the string "C:\" where "C" can be any letter, you'd use `/[A-Z]:\\/` — the first backslash escapes the one after it, so the expression searches for a single literal backslash.

 If using the `RegExp` constructor with a string literal, remember that the backslash is an escape in string literals, so to use it in the regular expression, you need to escape it at the string literal level.
 `/a\*b/` and `new RegExp("a\\*b")` create the same expression, which searches for "a" followed by a literal "\*" followed by "b".

If escape strings are not already part of your pattern you can add them using `String.prototype.replace()`:

```js
function escapeRegExp(string) {
  return string.replace(/[.\*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
```

 The "g" after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches.
 It is explained in detail below in Advanced Searching With Flags.

*Why isn't this built into JavaScript?* There is a proposal to add such a function to RegExp.

### Using parentheses

 Parentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered.
 Once remembered, the substring can be recalled for other use. See Groups and backreferences for more details.

Using regular expressions in JavaScript
---------------------------------------

Regular expressions are used with the `RegExp` methods `test()` and `exec()` and with the `String` methods `match()`, `matchAll()`, `replace()`, `replaceAll()`, `search()`, and `split()`.

| Method | Description |
| --- | --- |
| `exec()` | Executes a search for a match in a string. It returns an array of information or `null` on a mismatch. |
| `test()` | Tests for a match in a string. It returns `true` or `false`. |
| `match()` | Returns an array containing all of the matches, including capturing groups, or `null` if no match is found. |
| `matchAll()` | Returns an iterator containing all of the matches, including capturing groups. |
| `search()` | Tests for a match in a string. It returns the index of the match, or `-1` if the search fails. |
| `replace()` | Executes a search for a match in a string, and replaces the matched substring with a replacement substring. |
| `replaceAll()` | Executes a search for all matches in a string, and replaces the matched substrings with a replacement substring. |
| `split()` | Uses a regular expression or a fixed string to break a string into an array of substrings. |

 When you want to know whether a pattern is found in a string, use the `test()` or `search()` methods; for more information (but slower execution) use the `exec()` or `match()` methods.
 If you use `exec()` or `match()` and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, `RegExp`.
 If the match fails, the `exec()` method returns `null` (which coerces to `false`).

In the following example, the script uses the `exec()` method to find a match in a string.

```js
const myRe = /d(b+)d/g;
const myArray = myRe.exec("cdbbdbsbz");
```

If you do not need to access the properties of the regular expression, an alternative way of creating `myArray` is with this script:

```js
const myArray = /d(b+)d/g.exec("cdbbdbsbz");
// similar to 'cdbbdbsbz'.match(/d(b+)d/g); however,
// 'cdbbdbsbz'.match(/d(b+)d/g) outputs [ "dbbd" ]
// while /d(b+)d/g.exec('cdbbdbsbz') outputs [ 'dbbd', 'bb', index: 1, input: 'cdbbdbsbz' ]
```

(See Using the global search flag with `exec()` for further info about the different behaviors.)

If you want to construct the regular expression from a string, yet another alternative is this script:

```js
const myRe = new RegExp("d(b+)d", "g");
const myArray = myRe.exec("cdbbdbsbz");
```

With these scripts, the match succeeds and returns the array and updates the properties shown in the following table.

Results of regular expression execution.| Object | Property or index | Description | In this example |
| --- | --- | --- | --- |
| `myArray` |  | The matched string and all remembered substrings. | `['dbbd', 'bb', index: 1, input: 'cdbbdbsbz']` |
| `index` | The 0-based index of the match in the input string. | `1` |
| `input` | The original string. | `'cdbbdbsbz'` |
| `[0]` | The last matched characters. | `'dbbd'` |
| `myRe` | `lastIndex` |
 The index at which to start the next match.
 (This property is set only if the regular expression uses the g option, described in
 Advanced Searching With Flags.)
  | `5` |
| `source` | The text of the pattern. Updated at the time that the regular expression is created, not executed. | `'d(b+)d'` |

 As shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable.
 If you do, however, every occurrence is a new regular expression.
 For this reason, if you use this form without assigning it to a variable, you cannot subsequently access the properties of that regular expression.
 For example, assume you have this script:

```js
const myRe = /d(b+)d/g;
const myArray = myRe.exec("cdbbdbsbz");
console.log(`The value of lastIndex is ${myRe.lastIndex}`);

// "The value of lastIndex is 5"
```

However, if you have this script:

```js
const myArray = /d(b+)d/g.exec("cdbbdbsbz");
console.log(`The value of lastIndex is ${/d(b+)d/g.lastIndex}`);

// "The value of lastIndex is 0"
```

 The occurrences of `/d(b+)d/g` in the two statements are different regular expression objects and hence have different values for their `lastIndex` property.
 If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable.

### Advanced searching with flags

 Regular expressions have optional flags that allow for functionality like global searching and case-insensitive searching.
 These flags can be used separately or together in any order, and are included as part of the regular expression.

| Flag | Description | Corresponding property |
| --- | --- | --- |
| `d` | Generate indices for substring matches. | `hasIndices` |
| `g` | Global search. | `global` |
| `i` | Case-insensitive search. | `ignoreCase` |
| `m` | Allows `^` and `$` to match next to newline characters. | `multiline` |
| `s` | Allows `.` to match newline characters. | `dotAll` |
| `u` | "Unicode"; treat a pattern as a sequence of Unicode code points. | `unicode` |
| `v` | An upgrade to the `u` mode with more Unicode features. | `unicodeSets` |
| `y` | Perform a "sticky" search that matches starting at the current position in the target string. | `sticky` |

To include a flag with the regular expression, use this syntax:

```js
const re = /pattern/flags;
```

or

```js
const re = new RegExp("pattern", "flags");
```

Note that the flags are an integral part of a regular expression. They cannot be added or removed later.

For example, `re = /\w+\s/g` creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string.

```js
const re = /\w+\s/g;
const str = "fee fi fo fum";
const myArray = str.match(re);
console.log(myArray);

// ["fee ", "fi ", "fo "]
```

You could replace the line:

```js
const re = /\w+\s/g;
```

with:

```js
const re = new RegExp("\\w+\\s", "g");
```

and get the same result.

 The `m` flag is used to specify that a multiline input string should be treated as multiple lines.
 If the `m` flag is used, `^` and `$` match at the start or end of any line within the input string instead of the start or end of the entire string.

#### Using the global search flag with exec()

`RegExp.prototype.exec()` method with the `g` flag returns each match and its position iteratively.

```js
const str = "fee fi fo fum";
const re = /\w+\s/g;

console.log(re.exec(str)); // ["fee ", index: 0, input: "fee fi fo fum"]
console.log(re.exec(str)); // ["fi ", index: 4, input: "fee fi fo fum"]
console.log(re.exec(str)); // ["fo ", index: 7, input: "fee fi fo fum"]
console.log(re.exec(str)); // null
```

In contrast, `String.prototype.match()` method returns all matches at once, but without their position.

```js
console.log(str.match(re)); // ["fee ", "fi ", "fo "]
```

#### Using unicode regular expressions

The `u` flag is used to create "unicode" regular expressions; that is, regular expressions which support matching against unicode text. An important feature that's enabled in unicode mode is Unicode property escapes. For example, the following regular expression might be used to match against an arbitrary unicode "word":

```js
/\p{L}\*/u;
```

Unicode regular expressions have different execution behavior as well. `RegExp.prototype.unicode` contains more explanation about this.

Examples
--------

**Note:** Several examples are also available in:

* The reference pages for `exec()`, `test()`, `match()`, `matchAll()`, `search()`, `replace()`, `split()`
* The guide articles: character classes, assertions, groups and backreferences, quantifiers

### Using special characters to verify input

 In the following example, the user is expected to enter a phone number.
 When the user presses the "Check" button, the script checks the validity of the number.
 If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number.
 If the number is invalid, the script informs the user that the phone number is not valid.

The regular expression looks for:

1. the beginning of the line of data: `^`
2. followed by three numeric characters `\d{3}` OR `|` a left parenthesis `\(`, followed by three digits `\d{3}`, followed by a close parenthesis `\)`, in a non-capturing group `(?:)`
3. followed by one dash, forward slash, or decimal point in a capturing group `()`
4. followed by three digits `\d{3}`
5. followed by the match remembered in the (first) captured group `\1`
6. followed by four digits `\d{4}`
7. followed by the end of the line of data: `$`

#### HTML

```html
<p>
  Enter your phone number (with area code) and then click "Check".
  <br />
  The expected format is like ###-###-####.
</p>
<form id="form">
  <input id="phone" />
  <button type="submit">Check</button>
</form>
<p id="output"></p>
```

#### JavaScript

```js
const form = document.querySelector("#form");
const input = document.querySelector("#phone");
const output = document.querySelector("#output");

const re = /^(?:\d{3}|\(\d{3}\))([-/.])\d{3}\1\d{4}$/;

function testInfo(phoneInput) {
  const ok = re.exec(phoneInput.value);

  output.textContent = ok
    ? `Thanks, your phone number is ${ok[0]}`
    : `${phoneInput.value} isn't a phone number with area code!`;
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  testInfo(input);
});
```

#### Result

Tools
-----

RegExr

An online tool to learn, build, & test Regular Expressions.

Regex tester

An online regex builder/debugger

Regex interactive tutorial

An online interactive tutorials, Cheat sheet, & Playground.

Regex visualizer

An online visual regex tester.

* « Previous
* Next »


Using promises - JavaScript

Using promises
==============

* « Previous
* Next »

A `Promise` is an object representing the eventual completion or failure of an asynchronous operation. Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. Imagine a function, `createAudioFileAsync()`, which asynchronously generates a sound file given a configuration record and two callback functions: one called if the audio file is successfully created, and the other called if an error occurs.

Here's some code that uses `createAudioFileAsync()`:

```js
function successCallback(result) {
  console.log(`Audio file ready at URL: ${result}`);
}

function failureCallback(error) {
  console.error(`Error generating audio file: ${error}`);
}

createAudioFileAsync(audioSettings, successCallback, failureCallback);
```

If `createAudioFileAsync()` were rewritten to return a promise, you would attach your callbacks to it instead:

```js
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
```

This convention has several advantages. We will explore each one.

Chaining
--------

A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. In the old days, doing several asynchronous operations in a row would lead to the classic callback pyramid of doom:

```js
doSomething(function (result) {
  doSomethingElse(result, function (newResult) {
    doThirdThing(newResult, function (finalResult) {
      console.log(`Got the final result: ${finalResult}`);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);
```

With promises, we accomplish this by creating a promise chain. The API design of promises makes this great, because callbacks are attached to the returned promise object, instead of being passed into a function.

Here's the magic: the `then()` function returns a **new promise**, different from the original:

```js
const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);
```

This second promise (`promise2`) represents the completion not just of `doSomething()`, but also of the `successCallback` or `failureCallback` you passed in — which can be other asynchronous functions returning a promise. When that's the case, any callbacks added to `promise2` get queued behind the promise returned by either `successCallback` or `failureCallback`.

**Note:** If you want a working example to play with, you can use the following template to create any function returning a promise:

```js
function doSomething() {
  return new Promise((resolve) => {
    setTimeout(() => {
      // Other things to do before completion of the promise
      console.log("Did something");
      // The fulfillment value of the promise
      resolve("https://example.com/");
    }, 200);
  });
}
```

The implementation is discussed in the Creating a Promise around an old callback API section below.

With this pattern, you can create longer chains of processing, where each promise represents the completion of one asynchronous step in the chain. In addition, the arguments to `then` are optional, and `catch(failureCallback)` is short for `then(null, failureCallback)` — so if your error handling code is the same for all steps, you can attach it to the end of the chain:

```js
doSomething()
  .then(function (result) {
    return doSomethingElse(result);
  })
  .then(function (newResult) {
    return doThirdThing(newResult);
  })
  .then(function (finalResult) {
    console.log(`Got the final result: ${finalResult}`);
  })
  .catch(failureCallback);
```

You might see this expressed with arrow functions instead:

```js
doSomething()
  .then((result) => doSomethingElse(result))
  .then((newResult) => doThirdThing(newResult))
  .then((finalResult) => {
    console.log(`Got the final result: ${finalResult}`);
  })
  .catch(failureCallback);
```

**Note:** Arrow function expressions can have an implicit return; so, `() => x` is short for `() => { return x; }`.

`doSomethingElse` and `doThirdThing` can return any value — if they return promises, that promise is first waited until it settles, and the next callback receives the fulfillment value, not the promise itself. It is important to always return promises from `then` callbacks, even if the promise always resolves to `undefined`. If the previous handler started a promise but did not return it, there's no way to track its settlement anymore, and the promise is said to be "floating".

```js
doSomething()
  .then((url) => {
    // Missing `return` keyword in front of fetch(url).
    fetch(url);
  })
  .then((result) => {
    // result is undefined, because nothing is returned from the previous
    // handler. There's no way to know the return value of the fetch()
    // call anymore, or whether it succeeded at all.
  });
```

By returning the result of the `fetch` call (which is a promise), we can both track its completion and receive its value when it completes.

```js
doSomething()
  .then((url) => {
    // `return` keyword added
    return fetch(url);
  })
  .then((result) => {
    // result is a Response object
  });
```

Floating promises could be worse if you have race conditions — if the promise from the last handler is not returned, the next `then` handler will be called early, and any value it reads may be incomplete.

```js
const listOfIngredients = [];

doSomething()
  .then((url) => {
    // Missing `return` keyword in front of fetch(url).
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        listOfIngredients.push(data);
      });
  })
  .then(() => {
    console.log(listOfIngredients);
    // listOfIngredients will always be [], because the fetch request hasn't completed yet.
  });
```

Therefore, as a rule of thumb, whenever your operation encounters a promise, return it and defer its handling to the next `then` handler.

```js
const listOfIngredients = [];

doSomething()
  .then((url) => {
    // `return` keyword now included in front of fetch call.
    return fetch(url)
      .then((res) => res.json())
      .then((data) => {
        listOfIngredients.push(data);
      });
  })
  .then(() => {
    console.log(listOfIngredients);
    // listOfIngredients will now contain data from fetch call.
  });
```

Even better, you can flatten the nested chain into a single chain, which is simpler and makes error handling easier. The details are discussed in the Nesting section below.

```js
doSomething()
  .then((url) => fetch(url))
  .then((res) => res.json())
  .then((data) => {
    listOfIngredients.push(data);
  })
  .then(() => {
    console.log(listOfIngredients);
  });
```

Using `async`/`await` can help you write code that's more intuitive and resembles synchronous code. Below is the same example using `async`/`await`:

```js
async function logIngredients() {
  const url = await doSomething();
  const res = await fetch(url);
  const data = await res.json();
  listOfIngredients.push(data);
  console.log(listOfIngredients);
}
```

Note how the code looks exactly like synchronous code, except for the `await` keywords in front of promises. One of the only tradeoffs is that it may be easy to forget the `await` keyword, which can only be fixed when there's a type mismatch (e.g. trying to use a promise as a value).

`async`/`await` builds on promises — for example, `doSomething()` is the same function as before, so there's minimal refactoring needed to change from promises to `async`/`await`. You can read more about the `async`/`await` syntax in the async functions and `await` references.

**Note:** async/await has the same concurrency semantics as normal promise chains. `await` within one async function does not stop the entire program, only the parts that depend on its value, so other async jobs can still run while the `await` is pending.

Error handling
--------------

You might recall seeing `failureCallback` three times in the pyramid of doom earlier, compared to only once at the end of the promise chain:

```js
doSomething()
  .then((result) => doSomethingElse(result))
  .then((newResult) => doThirdThing(newResult))
  .then((finalResult) => console.log(`Got the final result: ${finalResult}`))
  .catch(failureCallback);
```

If there's an exception, the browser will look down the chain for `.catch()` handlers or `onRejected`. This is very much modeled after how synchronous code works:

```js
try {
  const result = syncDoSomething();
  const newResult = syncDoSomethingElse(result);
  const finalResult = syncDoThirdThing(newResult);
  console.log(`Got the final result: ${finalResult}`);
} catch (error) {
  failureCallback(error);
}
```

This symmetry with asynchronous code culminates in the `async`/`await` syntax:

```js
async function foo() {
  try {
    const result = await doSomething();
    const newResult = await doSomethingElse(result);
    const finalResult = await doThirdThing(newResult);
    console.log(`Got the final result: ${finalResult}`);
  } catch (error) {
    failureCallback(error);
  }
}
```

Promises solve a fundamental flaw with the callback pyramid of doom, by catching all errors, even thrown exceptions and programming errors. This is essential for functional composition of asynchronous operations. All errors are now handled by the `catch()` method at the end of the chain, and you should almost never need to use `try`/`catch` without using `async`/`await`.

### Nesting

In the examples above involving `listOfIngredients`, the first one has one promise chain nested in the return value of another `then()` handler, while the second one uses an entirely flat chain. Simple promise chains are best kept flat without nesting, as nesting can be a result of careless composition.

Nesting is a control structure to limit the scope of `catch` statements. Specifically, a nested `catch` only catches failures in its scope and below, not errors higher up in the chain outside the nested scope. When used correctly, this gives greater precision in error recovery:

```js
doSomethingCritical()
  .then((result) =>
    doSomethingOptional(result)
      .then((optionalResult) => doSomethingExtraNice(optionalResult))
      .catch((e) => {}),
  ) // Ignore if optional stuff fails; proceed.
  .then(() => moreCriticalStuff())
  .catch((e) => console.error(`Critical failure: ${e.message}`));
```

Note that the optional steps here are nested — with the nesting caused not by the indentation, but by the placement of the outer `(` and `)` parentheses around the steps.

The inner error-silencing `catch` handler only catches failures from `doSomethingOptional()` and `doSomethingExtraNice()`, after which the code resumes with `moreCriticalStuff()`. Importantly, if `doSomethingCritical()` fails, its error is caught by the final (outer) `catch` only, and does not get swallowed by the inner `catch` handler.

In `async`/`await`, this code looks like:

```js
async function main() {
  try {
    const result = await doSomethingCritical();
    try {
      const optionalResult = await doSomethingOptional(result);
      await doSomethingExtraNice(optionalResult);
    } catch (e) {
      // Ignore failures in optional steps and proceed.
    }
    await moreCriticalStuff();
  } catch (e) {
    console.error(`Critical failure: ${e.message}`);
  }
}
```

**Note:** If you don't have sophisticated error handling, you very likely don't need nested `then` handlers. Instead, use a flat chain and put the error handling logic at the end.

### Chaining after a catch

It's possible to chain *after* a failure, i.e. a `catch`, which is useful to accomplish new actions even after an action failed in the chain. Read the following example:

```js
doSomething()
  .then(() => {
    throw new Error("Something failed");

    console.log("Do this");
  })
  .catch(() => {
    console.error("Do that");
  })
  .then(() => {
    console.log("Do this, no matter what happened before");
  });
```

This will output the following text:
```

Initial
Do that
Do this, no matter what happened before
```

**Note:** The text "Do this" is not displayed because the "Something failed" error caused a rejection.

In `async`/`await`, this code looks like:

```js
async function main() {
  try {
    await doSomething();
    throw new Error("Something failed");
    console.log("Do this");
  } catch (e) {
    console.error("Do that");
  }
  console.log("Do this, no matter what happened before");
}
```

### Promise rejection events

If a promise rejection event is not handled by any handler, it bubbles to the top of the call stack, and the host needs to surface it. On the web, whenever a promise is rejected, one of two events is sent to the global scope (generally, this is either the `window` or, if being used in a web worker, it's the `Worker` or other worker-based interface). The two events are:

`unhandledrejection`

Sent when a promise is rejected but there is no rejection handler available.

`rejectionhandled`

Sent when a handler is attached to a rejected promise that has already caused an `unhandledrejection` event.

In both cases, the event (of type `PromiseRejectionEvent`) has as members a `promise` property indicating the promise that was rejected, and a `reason` property that provides the reason given for the promise to be rejected.

These make it possible to offer fallback error handling for promises, as well as to help debug issues with your promise management. These handlers are global per context, so all errors will go to the same event handlers, regardless of source.

In Node.js, handling promise rejection is slightly different. You capture unhandled rejections by adding a handler for the Node.js `unhandledRejection` event (notice the difference in capitalization of the name), like this:

```js
process.on("unhandledRejection", (reason, promise) => {
  // Add code here to examine the "promise" and "reason" values
});
```

For Node.js, to prevent the error from being logged to the console (the default action that would otherwise occur), adding that `process.on()` listener is all that's necessary; there's no need for an equivalent of the browser runtime's `preventDefault()` method.

However, if you add that `process.on` listener but don't also have code within it to handle rejected promises, they will just be dropped on the floor and silently ignored. So ideally, you should add code within that listener to examine each rejected promise and make sure it was not caused by an actual code bug.

Composition
-----------

There are four composition tools for running asynchronous operations concurrently: `Promise.all()`, `Promise.allSettled()`, `Promise.any()`, and `Promise.race()`.

We can start operations at the same time and wait for them all to finish like this:

```js
Promise.all([func1(), func2(), func3()]).then(([result1, result2, result3]) => {
  // use result1, result2 and result3
});
```

If one of the promises in the array rejects, `Promise.all()` immediately rejects the returned promise and aborts the other operations. This may cause unexpected state or behavior. `Promise.allSettled()` is another composition tool that ensures all operations are complete before resolving.

These methods all run promises concurrently — a sequence of promises are started simultaneously and do not wait for each other. Sequential composition is possible using some clever JavaScript:

```js
[func1, func2, func3]
  .reduce((p, f) => p.then(f), Promise.resolve())
  .then((result3) => {
    /\* use result3 \*/
  });
```

In this example, we reduce an array of asynchronous functions down to a promise chain. The code above is equivalent to:

```js
Promise.resolve()
  .then(func1)
  .then(func2)
  .then(func3)
  .then((result3) => {
    /\* use result3 \*/
  });
```

This can be made into a reusable compose function, which is common in functional programming:

```js
const applyAsync = (acc, val) => acc.then(val);
const composeAsync =
  (...funcs) =>
  (x) =>
    funcs.reduce(applyAsync, Promise.resolve(x));
```

The `composeAsync()` function accepts any number of functions as arguments and returns a new function that accepts an initial value to be passed through the composition pipeline:

```js
const transformData = composeAsync(func1, func2, func3);
const result3 = transformData(data);
```

Sequential composition can also be done more succinctly with async/await:

```js
let result;
for (const f of [func1, func2, func3]) {
  result = await f(result);
}
/\* use last result (i.e. result3) \*/
```

However, before you compose promises sequentially, consider if it's really necessary — it's always better to run promises concurrently so that they don't unnecessarily block each other unless one promise's execution depends on another's result.

Creating a Promise around an old callback API
---------------------------------------------

A `Promise` can be created from scratch using its constructor. This should be needed only to wrap old APIs.

In an ideal world, all asynchronous functions would already return promises. Unfortunately, some APIs still expect success and/or failure callbacks to be passed in the old way. The most obvious example is the `setTimeout()` function:

```js
setTimeout(() => saySomething("10 seconds passed"), 10 \* 1000);
```

Mixing old-style callbacks and promises is problematic. If `saySomething()` fails or contains a programming error, nothing catches it. This is intrinsic to the design of `setTimeout`.

Luckily we can wrap `setTimeout` in a promise. The best practice is to wrap the callback-accepting functions at the lowest possible level, and then never call them directly again:

```js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

wait(10 \* 1000)
  .then(() => saySomething("10 seconds"))
  .catch(failureCallback);
```

The promise constructor takes an executor function that lets us resolve or reject a promise manually. Since `setTimeout()` doesn't really fail, we left out reject in this case. For more information on how the executor function works, see the `Promise()` reference.

Timing
------

Lastly, we will look into the more technical details, about when the registered callbacks get called.

### Guarantees

In the callback-based API, when and how the callback gets called depends on the API implementor. For example, the callback may be called synchronously or asynchronously:

```js
function doSomething(callback) {
  if (Math.random() > 0.5) {
    callback();
  } else {
    setTimeout(() => callback(), 1000);
  }
}
```

The above design is strongly discouraged because it leads to the so-called "state of Zalgo". In the context of designing asynchronous APIs, this means a callback is called synchronously in some cases but asynchronously in other cases, creating ambiguity for the caller. For further background, see the article Designing APIs for Asynchrony, where the term was first formally presented. This API design makes side effects hard to analyze:

```js
let value = 1;
doSomething(() => {
  value = 2;
});
console.log(value); // 1 or 2?
```

On the other hand, promises are a form of inversion of control — the API implementor does not control when the callback gets called. Instead, the job of maintaining the callback queue and deciding when to call the callbacks is delegated to the promise implementation, and both the API user and API developer automatically gets strong semantic guarantees, including:

* Callbacks added with `then()` will never be invoked before the completion of the current run of the JavaScript event loop.
* These callbacks will be invoked even if they were added *after* the success or failure of the asynchronous operation that the promise represents.
* Multiple callbacks may be added by calling `then()` several times. They will be invoked one after another, in the order in which they were inserted.

To avoid surprises, functions passed to `then()` will never be called synchronously, even with an already-resolved promise:

```js
Promise.resolve().then(() => console.log(2));
console.log(1);
// Logs: 1, 2
```

Instead of running immediately, the passed-in function is put on a microtask queue, which means it runs later (only after the function which created it exits, and when the JavaScript execution stack is empty), just before control is returned to the event loop; i.e. pretty soon:

```js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

wait(0).then(() => console.log(4));
Promise.resolve()
  .then(() => console.log(2))
  .then(() => console.log(3));
console.log(1); // 1, 2, 3, 4
```

### Task queues vs. microtasks

Promise callbacks are handled as a microtask whereas `setTimeout()` callbacks are handled as task queues.

```js
const promise = new Promise((resolve, reject) => {
  console.log("Promise callback");
  resolve();
}).then((result) => {
  console.log("Promise callback (.then)");
});

setTimeout(() => {
  console.log("event-loop cycle: Promise (fulfilled)", promise);
}, 0);

console.log("Promise (pending)", promise);
```

The code above will output:
```

Promise callback
Promise (pending) Promise {<pending>}
Promise callback (.then)
event-loop cycle: Promise (fulfilled) Promise {<fulfilled>}
```

For more details, refer to Tasks vs. microtasks.

### When promises and tasks collide

If you run into situations in which you have promises and tasks (such as events or callbacks) which are firing in unpredictable orders, it's possible you may benefit from using a microtask to check status or balance out your promises when promises are created conditionally.

If you think microtasks may help solve this problem, see the microtask guide to learn more about how to use `queueMicrotask()` to enqueue a function as a microtask.

See also
--------

* `Promise`
* `async function`
* `await`
* Promises/A+ specification
* We have a problem with promises on pouchdb.com (2015)
* « Previous
* Next »


Regular expression syntax cheat sheet - JavaScript

Regular expression syntax cheat sheet
=====================================

This page provides an overall cheat sheet of all the capabilities of `RegExp` syntax by aggregating the content of the articles in the `RegExp` guide. If you need more information on a specific topic, please follow the link on the corresponding heading to access the full article or head to the guide.

Character classes
-----------------

Character classes distinguish kinds of characters such as, for example, distinguishing between letters and digits.

| Characters | Meaning |
| --- | --- |
| `[xyz][a-c]` |
 A character class. Matches any one of the enclosed characters. You can
 specify a range of characters by using a hyphen, but if the hyphen
 appears as the first or last character enclosed in the square brackets,
 it is taken as a literal hyphen to be included in the character class
 as a normal character.

 For example, `[abcd]` is the same as `[a-d]`.
 They match the "b" in "brisket", and the "a" or the "c" in "arch",
 but not the "-" (hyphen) in "non-profit".

 For example, `[abcd-]` and `[-abcd]` match the
 "b" in "brisket", the "a" or the "c" in "arch", and the "-" (hyphen)
 in "non-profit".

 For example, `[\w-]` is the same as
 `[A-Za-z0-9_-]`. They both match any of the characters in
 "no\_reply@example-server.com" except for the "@" and the ".".
  |
| `[^xyz][^a-c]` |
 A negated or complemented character class. That is, it matches
 anything that is not enclosed in the square brackets. You can specify a range
 of characters by using a hyphen, but if the hyphen appears as the
 first or last character enclosed in the square brackets, it is taken as
 a literal hyphen to be included in the character class as a normal
 character. For example, `[^abc]` is the same as
 `[^a-c]`. They initially match "o" in "bacon" and "h" in
 "chop".

**Note:** The ^ character may also indicate the
 beginning of input.

 |
| `.` | Has one of the following meanings:* Matches any single character *except* line terminators:
 `\n`, `\r`, `\u2028` or
 `\u2029`. For example, `/.y/` matches "my" and
 "ay", but not "yes", in "yes make my day".
* Inside a character class, the dot loses its special meaning and
 matches a literal dot.

 Note that the `m` multiline flag doesn't change the dot
 behavior. So to match a pattern across multiple lines, the character
 class `[^]` can be used — it will match any character
 including newlines.

 The `s` "dotAll" flag allows the dot to
 also match line terminators.
  |
| `\d` |
 Matches any digit (Arabic numeral). Equivalent to `[0-9]`.
 For example, `/\d/` or `/[0-9]/` matches "2" in
 "B2 is the suite number".
  |
| `\D` |
 Matches any character that is not a digit (Arabic numeral). Equivalent
 to `[^0-9]`. For example, `/\D/` or
 `/[^0-9]/` matches "B" in "B2 is the suite number".
  |
| `\w` |
 Matches any alphanumeric character from the basic Latin alphabet,
 including the underscore. Equivalent to `[A-Za-z0-9_]`. For
 example, `/\w/` matches "a" in "apple", "5" in "$5.28", and
 "3" in "3D".
  |
| `\W` |
 Matches any character that is not a word character from the basic
 Latin alphabet. Equivalent to `[^A-Za-z0-9_]`. For example,
 `/\W/` or `/[^A-Za-z0-9_]/` matches "%" in
 "50%".
  |
| `\s` |
 Matches a single white space character, including space, tab, form
 feed, line feed, and other Unicode spaces. Equivalent to
 `[
\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]`. For example, `/\s\w*/` matches " bar" in "foo bar".
  |
| `\S` |
 Matches a single character other than white space. Equivalent to
 `[^
\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]`. For example, `/\S\w*/` matches "foo" in "foo bar".
  |
| `\t` | Matches a horizontal tab. |
| `\r` | Matches a carriage return. |
| `\n` | Matches a linefeed. |
| `\v` | Matches a vertical tab. |
| `\f` | Matches a form-feed. |
| `[\b]` |
 Matches a backspace. If you're looking for the word-boundary character
 (`\b`), see
 Boundaries.
  |
| `\0` | Matches a NUL character. Do not follow this with another digit. |
| `\c*X*` |
 Matches a control character using
 caret notation, where "X" is a letter from A–Z (corresponding to code points
 `U+0001`*–*`U+001F`). For example,
 `/\cM/` matches "\r" in "\r\n".
  |
| `\x*hh*` |
 Matches the character with the code `*hh*` (two
 hexadecimal digits).
  |
| `\u*hhhh*` |
 Matches a UTF-16 code-unit with the value
 `*hhhh*` (four hexadecimal digits).
  |
| `\u*{hhhh}* or *\u{hhhhh}*` |
 (Only when the `u` flag is set.) Matches the character with
 the Unicode value `U+*hhhh*` or `U+*hhhhh*`
 (hexadecimal digits).
  |
| `\` |
 Indicates that the following character should be treated specially, or
 "escaped". It behaves one of two ways.
 * For characters that are usually treated literally, indicates that
 the next character is special and not to be interpreted literally.
 For example, `/b/` matches the character "b". By placing
 a backslash in front of "b", that is by using `/\b/`, the
 character becomes special to mean match a word boundary.
* For characters that are usually treated specially, indicates that
 the next character is not special and should be interpreted
 literally. For example, "\*" is a special character that means 0 or
 more occurrences of the preceding character should be matched; for
 example, `/a*/` means match 0 or more "a"s. To match
 `*` literally, precede it with a backslash; for example,
 `/a\*/` matches "a\*".

 Note that some characters like `:`, `-`,
 `@`, etc. neither have a special meaning when escaped nor
 when unescaped. Escape sequences like `\:`,
 `\-`, `\@` will be equivalent to their literal,
 unescaped character equivalents in regular expressions. However, in
 regular expressions with the
 unicode flag, these will cause an *invalid identity escape* error. This is
 done to ensure backward compatibility with existing code that uses new
 escape sequences like `\p` or `\k`.

**Note:** To match this character literally, escape it
 with itself. In other words to search for `\` use
 `/\\/`.

 |
| `*x*|*y*` |
**Disjunction:** Matches either "x" or "y". Each component, separated by a pipe (`|`), is called an *alternative*. For example,
 `/green|red/` matches "green" in "green apple" and "red" in
 "red apple".

**Note:** A disjunction is another way to specify "a set of choices", but it's not a character class. Disjunctions are not atoms — you need to use a group to make it part of a bigger pattern. `[abc]` is functionally equivalent to `(?:a|b|c)`.
 |

Assertions
----------

Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).

### Boundary-type assertions

| Characters | Meaning |
| --- | --- |
| `^` |
 Matches the beginning of input. If the multiline flag is set to true,
 also matches immediately after a line break character. For example,
 `/^A/` does not match the "A" in "an A", but does match the
 first "A" in "An A".

**Note:** This character has a different meaning when
 it appears at the start of a
 character class.

 |
| `$` |
 Matches the end of input. If the multiline flag is set to true, also
 matches immediately before a line break character. For example,
 `/t$/` does not match the "t" in "eater", but does match it
 in "eat".
  |
| `\b` |
 Matches a word boundary. This is the position where a word character
 is not followed or preceded by another word-character, such as between
 a letter and a space. Note that a matched word boundary is not
 included in the match. In other words, the length of a matched word
 boundary is zero.

Examples:* `/\bm/` matches the "m" in "moon".
* `/oo\b/` does not match the "oo" in "moon", because "oo"
 is followed by "n" which is a word character.
* `/oon\b/` matches the "oon" in "moon", because "oon" is
 the end of the string, thus not followed by a word character.
* `/\w\b\w/` will never match anything, because a word
 character can never be followed by both a non-word and a word
 character.

 To match a backspace character (`[\b]`), see
 Character Classes.
  |
| `\B` |
 Matches a non-word boundary. This is a position where the previous and
 next character are of the same type: Either both must be words, or
 both must be non-words, for example between two letters or between two
 spaces. The beginning and end of a string are considered non-words.
 Same as the matched word boundary, the matched non-word boundary is
 also not included in the match. For example,
 `/\Bon/` matches "on" in "at noon", and
 `/ye\B/` matches "ye" in "possibly yesterday".
  |

### Other assertions

**Note:** The `?` character may also be used as a quantifier.

| Characters | Meaning |
| --- | --- |
| `x(?=y)` |
**Lookahead assertion:** Matches "x" only if "x" is
 followed by "y". For example, /`Jack(?=Sprat)/` matches
 "Jack" only if it is followed by "Sprat".`/Jack(?=Sprat|Frost)/`
 matches "Jack" only if it is followed by "Sprat" or "Frost". However,
 neither "Sprat" nor "Frost" is part of the match results.
  |
| `x(?!y)` |
**Negative lookahead assertion:** Matches "x" only if "x"
 is not followed by "y". For example, `/\d+(?!\.)/` matches
 a number only if it is not followed by a decimal point. `/\d+(?!\.)/.exec('3.141')`
 matches "141" but not "3".
  |
| `(?<=y)x` |
**Lookbehind assertion:** Matches "x" only if "x" is
 preceded by "y". For example,
 `/(?<=Jack)Sprat/` matches "Sprat" only if it is
 preceded by "Jack". `/(?<=Jack|Tom)Sprat/` matches
 "Sprat" only if it is preceded by "Jack" or "Tom". However, neither
 "Jack" nor "Tom" is part of the match results.
  |
| `(?<!y)x` |
**Negative lookbehind assertion:** Matches "x" only if
 "x" is not preceded by "y". For example,
 `/(?<!-)\d+/` matches a number only if it is not
 preceded by a minus sign. `/(?<!-)\d+/.exec('3')`
 matches "3". `/(?<!-)\d+/.exec('-3')` match is not
 found because the number is preceded by the minus sign.
  |

Groups and backreferences
-------------------------

Groups and backreferences indicate groups of expression characters.

| Characters | Meaning |
| --- | --- |
| `(*x*)` |
**Capturing group:** Matches `*x*` and
 remembers the match. For example, `/(foo)/` matches and
 remembers "foo" in "foo bar".

 A regular expression may have multiple capturing groups. In results,
 matches to capturing groups typically in an array whose members are in
 the same order as the left parentheses in the capturing group. This is
 usually just the order of the capturing groups themselves. This
 becomes important when capturing groups are nested. Matches are
 accessed using the index of the result's elements (`[1], …, [n]`) or from the predefined `RegExp` object's properties
 (`$1, …, $9`).

 Capturing groups have a performance penalty. If you don't need the
 matched substring to be recalled, prefer non-capturing parentheses
 (see below).

`String.prototype.match()`
 won't return groups if the `/.../g` flag is set. However,
 you can still use
 `String.prototype.matchAll()`
 to get all matches.
  |
| `(?<Name>x)` |
**Named capturing group:** Matches "x" and stores it on
 the groups property of the returned matches under the name specified
 by `<Name>`. The angle brackets (`<`
 and `>`) are required for group name.

 For example, to extract the United States area code from a phone
 number, we could use `/\((?<area>\d\d\d)\)/`. The
 resulting number would appear under `matches.groups.area`.
  |
| `(?:*x*)` | **Non-capturing group:** Matches "x" but does not remember
 the match. The matched substring cannot be recalled from the resulting
 array's elements (`[1], …, [n]`) or from the predefined
 `RegExp` object's properties (`$1, …, $9`).
  |
| `\*n*` |
 Where "n" is a positive integer. A back reference to the last
 substring matching the n parenthetical in the regular expression
 (counting left parentheses). For example,
 `/apple(,)\sorange\1/` matches "apple, orange," in "apple,
 orange, cherry, peach".
  |
| \k<Name> | A back reference to the last substring matching the **Named capture group** specified by `<Name>`.
For example, `/(?<title>\w+), yes \k<title>/` matches "Sir, yes Sir" in "Do you copy? Sir, yes Sir!".

**Note:** `\k` is used literally here to
 indicate the beginning of a back reference to a Named capture group.

 |

Quantifiers
-----------

Quantifiers indicate numbers of characters or expressions to match.

**Note:** In the following, *item* refers not only to singular characters, but also includes character classes and groups and backreferences.

| Characters | Meaning |
| --- | --- |
| `*x**` |
 Matches the preceding item "x" 0 or more times. For example,
 `/bo*/` matches "boooo" in "A ghost booooed" and "b" in "A
 bird warbled", but nothing in "A goat grunted".
  |
| `*x*+` |
 Matches the preceding item "x" 1 or more times. Equivalent to
 `{1,}`. For example, `/a+/` matches the "a" in
 "candy" and all the "a"'s in "caaaaaaandy".
  |
| `*x*?` |
 Matches the preceding item "x" 0 or 1 times. For example,
 `/e?le?/` matches the "el" in "angel" and the "le" in
 "angle."

 If used immediately after any of the quantifiers `*`,
 `+`, `?`, or `{}`, makes the
 quantifier non-greedy (matching the minimum number of times), as
 opposed to the default, which is greedy (matching the maximum number
 of times).
  |
| `*x*{*n*}` |
 Where "n" is a positive integer, matches exactly "n" occurrences of
 the preceding item "x". For example, `/a{2}/` doesn't match
 the "a" in "candy", but it matches all of the "a"'s in "caandy", and
 the first two "a"'s in "caaandy".
  |
| `*x*{*n*,}` |
 Where "n" is a positive integer, matches at least "n" occurrences of
 the preceding item "x". For example, `/a{2,}/` doesn't
 match the "a" in "candy", but matches all of the a's in "caandy" and
 in "caaaaaaandy".
  |
| `*x*{*n*,*m*}` |
 Where "n" is 0 or a positive integer, "m" is a positive integer, and
 `*m* > *n*`, matches at least "n" and at most "m" occurrences of the preceding
 item "x". For example, `/a{1,3}/` matches nothing in
 "cndy", the "a" in "candy", the two "a"'s in "caandy", and the first
 three "a"'s in "caaaaaaandy". Notice that when matching "caaaaaaandy",
 the match is "aaa", even though the original string had more "a"s in
 it.
  |
| `*x**?``*x*+?``*x*??``*x*{n}?``*x*{n,}?``*x*{n,m}?` |
 By default quantifiers like `*` and `+` are
 "greedy", meaning that they try to match as much of the string as
 possible. The `?` character after the quantifier makes the
 quantifier "non-greedy": meaning that it will stop as soon as it finds
 a match. For example, given a string like "some <foo> <bar>
 new </bar> </foo> thing":
 * `/<.*>/` will match "<foo> <bar> new
 </bar> </foo>"
* `/<.*?>/` will match "<foo>"
 |


Assertions - JavaScript

Assertions
==========

Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).

Try it
------

Types
-----

### Boundary-type assertions

| Characters | Meaning |
| --- | --- |
| `^` |
 Matches the beginning of input. If the multiline flag is set to true,
 also matches immediately after a line break character. For example,
 `/^A/` does not match the "A" in "an A", but does match the
 first "A" in "An A".

**Note:** This character has a different meaning when
 it appears at the start of a
 character class.

 |
| `$` |
 Matches the end of input. If the multiline flag is set to true, also
 matches immediately before a line break character. For example,
 `/t$/` does not match the "t" in "eater", but does match it
 in "eat".
  |
| `\b` |
 Matches a word boundary. This is the position where a word character
 is not followed or preceded by another word-character, such as between
 a letter and a space. Note that a matched word boundary is not
 included in the match. In other words, the length of a matched word
 boundary is zero.

Examples:* `/\bm/` matches the "m" in "moon".
* `/oo\b/` does not match the "oo" in "moon", because "oo"
 is followed by "n" which is a word character.
* `/oon\b/` matches the "oon" in "moon", because "oon" is
 the end of the string, thus not followed by a word character.
* `/\w\b\w/` will never match anything, because a word
 character can never be followed by both a non-word and a word
 character.

 To match a backspace character (`[\b]`), see
 Character Classes.
  |
| `\B` |
 Matches a non-word boundary. This is a position where the previous and
 next character are of the same type: Either both must be words, or
 both must be non-words, for example between two letters or between two
 spaces. The beginning and end of a string are considered non-words.
 Same as the matched word boundary, the matched non-word boundary is
 also not included in the match. For example,
 `/\Bon/` matches "on" in "at noon", and
 `/ye\B/` matches "ye" in "possibly yesterday".
  |

### Other assertions

**Note:** The `?` character may also be used as a quantifier.

| Characters | Meaning |
| --- | --- |
| `x(?=y)` |
**Lookahead assertion:** Matches "x" only if "x" is
 followed by "y". For example, `/Jack(?=Sprat)/` matches
 "Jack" only if it is followed by "Sprat".`/Jack(?=Sprat|Frost)/`
 matches "Jack" only if it is followed by "Sprat" or "Frost". However,
 neither "Sprat" nor "Frost" is part of the match results.
  |
| `x(?!y)` |
**Negative lookahead assertion:** Matches "x" only if "x"
 is not followed by "y". For example, `/\d+(?!\.)/` matches
 a number only if it is not followed by a decimal point. `/\d+(?!\.)/.exec('3.141')`
 matches "141" but not "3".
  |
| `(?<=y)x` |
**Lookbehind assertion:** Matches "x" only if "x" is
 preceded by "y". For example,
 `/(?<=Jack)Sprat/` matches "Sprat" only if it is
 preceded by "Jack". `/(?<=Jack|Tom)Sprat/` matches
 "Sprat" only if it is preceded by "Jack" or "Tom". However, neither
 "Jack" nor "Tom" is part of the match results.
  |
| `(?<!y)x` |
**Negative lookbehind assertion:** Matches "x" only if
 "x" is not preceded by "y". For example,
 `/(?<!-)\d+/` matches a number only if it is not
 preceded by a minus sign. `/(?<!-)\d+/.exec('3')`
 matches "3". `/(?<!-)\d+/.exec('-3')` match is not
 found because the number is preceded by the minus sign.
  |

Examples
--------

### General boundary-type overview example

```js
// Using Regex boundaries to fix buggy string.
buggyMultiline = `tey, ihe light-greon apple
tangs on ihe greon traa`;

// 1) Use ^ to fix the matching at the beginning of the string, and right after newline.
buggyMultiline = buggyMultiline.replace(/^t/gim, "h");
console.log(1, buggyMultiline); // fix 'tey' => 'hey' and 'tangs' => 'hangs' but do not touch 'traa'.

// 2) Use $ to fix matching at the end of the text.
buggyMultiline = buggyMultiline.replace(/aa$/gim, "ee.");
console.log(2, buggyMultiline); // fix 'traa' => 'tree.'.

// 3) Use \b to match characters right on border between a word and a space.
buggyMultiline = buggyMultiline.replace(/\bi/gim, "t");
console.log(3, buggyMultiline); // fix 'ihe' => 'the' but do not touch 'light'.

// 4) Use \B to match characters inside borders of an entity.
fixedMultiline = buggyMultiline.replace(/\Bo/gim, "e");
console.log(4, fixedMultiline); // fix 'greon' => 'green' but do not touch 'on'.
```

### Matching the beginning of input using a ^ control character

Use `^` for matching at the beginning of input. In this example, we can get the fruits that start with 'A' by a `/^A/` regex. For selecting appropriate fruits we can use the filter method with an arrow function.

```js
const fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"];

// Select fruits started with 'A' by /^A/ Regex.
// Here '^' control symbol used only in one role: Matching beginning of an input.

const fruitsStartsWithA = fruits.filter((fruit) => /^A/.test(fruit));
console.log(fruitsStartsWithA); // [ 'Apple', 'Avocado' ]
```

In the second example `^` is used both for matching at the beginning of input and for creating negated or complemented character class when used within character classes.

```js
const fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"];

// Selecting fruits that do not start by 'A' with a /^[^A]/ regex.
// In this example, two meanings of '^' control symbol are represented:
// 1) Matching beginning of the input
// 2) A negated or complemented character class: [^A]
// That is, it matches anything that is not enclosed in the square brackets.

const fruitsStartsWithNotA = fruits.filter((fruit) => /^[^A]/.test(fruit));

console.log(fruitsStartsWithNotA); // [ 'Watermelon', 'Orange', 'Strawberry' ]
```

### Matching a word boundary

```js
const fruitsWithDescription = ["Red apple", "Orange orange", "Green Avocado"];

// Select descriptions that contains 'en' or 'ed' words endings:
const enEdSelection = fruitsWithDescription.filter((descr) =>
  /(en|ed)\b/.test(descr),
);

console.log(enEdSelection); // [ 'Red apple', 'Green Avocado' ]
```

### Lookahead assertion

```js
// JS Lookahead assertion x(?=y)

const regex = /First(?= test)/g;

console.log("First test".match(regex)); // [ 'First' ]
console.log("First peach".match(regex)); // null
console.log("This is a First test in a year.".match(regex)); // [ 'First' ]
console.log("This is a First peach in a month.".match(regex)); // null
```

### Basic negative lookahead assertion

For example, `/\d+(?!\.)/` matches a number only if it is not followed by a decimal point. `/\d+(?!\.)/.exec('3.141')` matches "141" but not "3.

```js
console.log(/\d+(?!\.)/g.exec("3.141")); // [ '141', index: 2, input: '3.141' ]
```

### Different meaning of '?!' combination usage in assertions and character classes

The `?!` combination has different meanings in assertions like `/x(?!y)/` and character classes like `[^?!]`.

```js
const orangeNotLemon =
  "Do you want to have an orange? Yes, I do not want to have a lemon!";

// Different meaning of '?!' combination usage in Assertions /x(?!y)/ and Ranges /[^?!]/
const selectNotLemonRegex = /[^?!]+have(?! a lemon)[^?!]+[?!]/gi;
console.log(orangeNotLemon.match(selectNotLemonRegex)); // [ 'Do you want to have an orange?' ]

const selectNotOrangeRegex = /[^?!]+have(?! an orange)[^?!]+[?!]/gi;
console.log(orangeNotLemon.match(selectNotOrangeRegex)); // [ ' Yes, I do not want to have a lemon!' ]
```

### Lookbehind assertion

```js
const oranges = ["ripe orange A", "green orange B", "ripe orange C"];

const ripeOranges = oranges.filter((fruit) => /(?<=ripe )orange/.test(fruit));
console.log(ripeOranges); // [ 'ripe orange A', 'ripe orange C' ]
```

See also
--------

* Regular expressions guide
* Character classes guide
* Quantifiers guide
* Groups and backreferences guide
* `RegExp`


Groups and backreferences - JavaScript

Groups and backreferences
=========================

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.

Try it
------

Types
-----

| Characters | Meaning |
| --- | --- |
| `(*x*)` |
**Capturing group:** Matches `*x*` and
 remembers the match. For example, `/(foo)/` matches and
 remembers "foo" in "foo bar".

 A regular expression may have multiple capturing groups. In results,
 matches to capturing groups typically in an array whose members are in
 the same order as the left parentheses in the capturing group. This is
 usually just the order of the capturing groups themselves. This
 becomes important when capturing groups are nested. Matches are
 accessed using the index of the result's elements (`[1], …, [n]`) or from the predefined `RegExp` object's properties
 (`$1, …, $9`).

 Capturing groups have a performance penalty. If you don't need the
 matched substring to be recalled, prefer non-capturing parentheses
 (see below).

`String.prototype.match()`
 won't return groups if the `/.../g` flag is set. However,
 you can still use
 `String.prototype.matchAll()`
 to get all matches.
  |
| `(?<Name>x)` |
**Named capturing group:** Matches "x" and stores it on
 the groups property of the returned matches under the name specified
 by `<Name>`. The angle brackets (`<`
 and `>`) are required for group name.

 For example, to extract the United States area code from a phone
 number, we could use `/\((?<area>\d\d\d)\)/`. The
 resulting number would appear under `matches.groups.area`.
  |
| `(?:*x*)` | **Non-capturing group:** Matches "x" but does not remember
 the match. The matched substring cannot be recalled from the resulting
 array's elements (`[1], …, [n]`) or from the predefined
 `RegExp` object's properties (`$1, …, $9`).
  |
| `\*n*` |
 Where "n" is a positive integer. A back reference to the last
 substring matching the n parenthetical in the regular expression
 (counting left parentheses). For example,
 `/apple(,)\sorange\1/` matches "apple, orange," in "apple,
 orange, cherry, peach".
  |
| `\k<Name>` |
 A back reference to the last substring matching the
 **Named capture group** specified by
 `<Name>`.

 For example,
 `/(?<title>\w+), yes \k<title>/` matches "Sir,
 yes Sir" in "Do you copy? Sir, yes Sir!".

**Note:** `\k` is used literally here to
 indicate the beginning of a back reference to a Named capture group.

 |

Examples
--------

### Using groups

```js
const personList = `First\_Name: John, Last\_Name: Doe
First\_Name: Jane, Last\_Name: Smith`;

const regexpNames = /First\_Name: (\w+), Last\_Name: (\w+)/gm;
for (const match of personList.matchAll(regexpNames)) {
  console.log(`Hello ${match[1]} ${match[2]}`);
}
```

### Using named groups

```js
const personList = `First\_Name: John, Last\_Name: Doe
First\_Name: Jane, Last\_Name: Smith`;

const regexpNames =
  /First\_Name: (?<firstname>\w+), Last\_Name: (?<lastname>\w+)/gm;
for (const match of personList.matchAll(regexpNames)) {
  console.log(`Hello ${match.groups.firstname} ${match.groups.lastname}`);
}
```

### Using groups and back references

```js
const quote = `Single quote "'" and double quote '"'`;
const regexpQuotes = /(['"]).\*?\1/g;
for (const match of quote.matchAll(regexpQuotes)) {
  console.log(match[0]);
}
```

### Using groups and match indices

By providing the `d` flag, the indices of each capturing group is returned. This is especially useful if you are correlating each matched group with the original text — for example, to provide compiler diagnostics.

```js
const code = `function add(x, y) {
 return x + y;
}`;
const functionRegexp =
  /(function\s+)(?<name>[$\_\p{ID\_Start}][$\u200c\u200d\p{ID\_Continue}]\*)/du;
const match = functionRegexp.exec(code);
const lines = code.split("\n");
lines.splice(
  1,
  0,
  " ".repeat(match.indices[1][1] - match.indices[1][0]) +
    "^".repeat(match.indices.groups.name[1] - match.indices.groups.name[0]),
);
console.log(lines.join("\n"));
// function add(x, y) {
// ^^^
// return x + y;
// }
```

See also
--------

* Regular expressions guide
* Character classes guide
* Assertions guide
* Quantifiers guide
* `RegExp`


Character classes - JavaScript

Character classes
=================

Character classes distinguish kinds of characters such as, for example, distinguishing between letters and digits.

Try it
------

Types
-----

| Characters | Meaning |
| --- | --- |
| `[xyz][a-c]` |
 A character class. Matches any one of the enclosed characters. You can
 specify a range of characters by using a hyphen, but if the hyphen
 appears as the first or last character enclosed in the square brackets,
 it is taken as a literal hyphen to be included in the character class
 as a normal character.

 For example, `[abcd]` is the same as `[a-d]`.
 They match the "b" in "brisket", and the "c" in "chop".

 For example, `[abcd-]` and `[-abcd]` match the
 "b" in "brisket", the "c" in "chop", and the "-" (hyphen) in
 "non-profit".

 For example, `[\w-]` is the same as
 `[A-Za-z0-9_-]`. They both match the "b" in "brisket", the
 "c" in "chop", and the "n" in "non-profit".
  |
| `[^xyz][^a-c]` |
 A negated or complemented character class. That is, it matches
 anything that is not enclosed in the square brackets. You can specify a range
 of characters by using a hyphen, but if the hyphen appears as the
 first character after the `^` or the last character enclosed in the square brackets, it is taken as
 a literal hyphen to be included in the character class as a normal
 character. For example, `[^abc]` is the same as
 `[^a-c]`. They initially match "o" in "bacon" and "h" in
 "chop".

**Note:** The ^ character may also indicate the
 beginning of input.

 |
| `.` | Has one of the following meanings:* Matches any single character *except* line terminators:
 `\n`, `\r`, `\u2028` or
 `\u2029`. For example, `/.y/` matches "my" and
 "ay", but not "yes", in "yes make my day", as there is no character before "y" in "yes".
* Inside a character class, the dot loses its special meaning and
 matches a literal dot.

 Note that the `m` multiline flag doesn't change the dot
 behavior. So to match a pattern across multiple lines, the character
 class `[^]` can be used — it will match any character
 including newlines.

 The `s` "dotAll" flag allows the dot to
 also match line terminators.
  |
| `\d` |
 Matches any digit (Arabic numeral). Equivalent to `[0-9]`.
 For example, `/\d/` or `/[0-9]/` matches "2" in
 "B2 is the suite number".
  |
| `\D` |
 Matches any character that is not a digit (Arabic numeral). Equivalent
 to `[^0-9]`. For example, `/\D/` or
 `/[^0-9]/` matches "B" in "B2 is the suite number".
  |
| `\w` |
 Matches any alphanumeric character from the basic Latin alphabet,
 including the underscore. Equivalent to `[A-Za-z0-9_]`. For
 example, `/\w/` matches "a" in "apple", "5" in "$5.28", "3"
 in "3D" and "m" in "Émanuel".
  |
| `\W` |
 Matches any character that is not a word character from the basic
 Latin alphabet. Equivalent to `[^A-Za-z0-9_]`. For example,
 `/\W/` or `/[^A-Za-z0-9_]/` matches "%" in "50%"
 and "É" in "Émanuel".
  |
| `\s` |
 Matches a single white space character, including space, tab, form
 feed, line feed, and other Unicode spaces. Equivalent to
 `[\f\n\r\t\v\u0020\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]`. For example, `/\s\w*/` matches " bar" in "foo bar".
  |
| `\S` |
 Matches a single character other than white space. Equivalent to
 `[^\f\n\r\t\v\u0020\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]`. For example, `/\S\w*/` matches "foo" in "foo bar".
  |
| `\t` | Matches a horizontal tab. |
| `\r` | Matches a carriage return. |
| `\n` | Matches a linefeed. |
| `\v` | Matches a vertical tab. |
| `\f` | Matches a form-feed. |
| `[\b]` |
 Matches a backspace. If you're looking for the word-boundary character
 (`\b`), see
 Assertions.
  |
| `\0` | Matches a NUL character. Do not follow this with another digit. |
| `\c*X*` |
 Matches a control character using
 caret notation, where "X" is a letter from A–Z (corresponding to code points
 `U+0001`*–*`U+001A`). For example,
 `/\cM\cJ/` matches "\r\n".
  |
| `\x*hh*` |
 Matches the character with the code `*hh*` (two
 hexadecimal digits).
  |
| `\u*hhhh*` |
 Matches a UTF-16 code-unit with the value
 `*hhhh*` (four hexadecimal digits).
  |
| `\u*{hhhh}* or *\u{hhhhh}*` |
 (Only when the `u` flag is set.) Matches the character with
 the Unicode value `U+*hhhh*` or `U+*hhhhh*`
 (hexadecimal digits).
  |
| `\p{*UnicodeProperty*}`,
 `\P{*UnicodeProperty*}` |
 Matches a character based on its
 Unicode character properties
 (to match just, for example, emoji characters, or Japanese
 *katakana* characters, or Chinese/Japanese Han/Kanji characters,
 etc.).
  |
| `\` |
 Indicates that the following character should be treated specially, or
 "escaped". It behaves one of two ways.
 * For characters that are usually treated literally, indicates that
 the next character is special and not to be interpreted literally.
 For example, `/b/` matches the character "b". By placing
 a backslash in front of "b", that is by using `/\b/`, the
 character becomes special to mean match a word boundary.
* For characters that are usually treated specially, indicates that
 the next character is not special and should be interpreted
 literally. For example, "\*" is a special character that means 0 or
 more occurrences of the preceding character should be matched; for
 example, `/a*/` means match 0 or more "a"s. To match
 `*` literally, precede it with a backslash; for example,
 `/a\*/` matches "a\*".

**Note:** To match this character literally, escape it
 with itself. In other words to search for `\` use
 `/\\/`.

 |
| `*x*|*y*` |
**Disjunction:** Matches either "x" or "y". Each component, separated by a pipe (`|`), is called an *alternative*. For example,
 `/green|red/` matches "green" in "green apple" and "red" in
 "red apple".

**Note:** A disjunction is another way to specify "a set of choices", but it's not a character class. Disjunctions are not atoms — you need to use a group to make it part of a bigger pattern. `[abc]` is functionally equivalent to `(?:a|b|c)`.
 |

Examples
--------

### Looking for a series of digits

```js
const randomData = "015 354 8787 687351 3512 8735";
const regexpFourDigits = /\b\d{4}\b/g;
// \b indicates a boundary (i.e. do not start matching in the middle of a word)
// \d{4} indicates a digit, four times
// \b indicates another boundary (i.e. do not end matching in the middle of a word)

console.table(randomData.match(regexpFourDigits));
// ['8787', '3512', '8735']
```

### Looking for a word (from the latin alphabet) starting with A

```js
const aliceExcerpt =
  "I'm sure I'm not Ada,' she said, 'for her hair goes in such long ringlets, and mine doesn't go in ringlets at all.";
const regexpWordStartingWithA = /\b[aA]\w+/g;
// \b indicates a boundary (i.e. do not start matching in the middle of a word)
// [aA] indicates the letter a or A
// \w+ indicates any character \*from the latin alphabet\*, multiple times

console.table(aliceExcerpt.match(regexpWordStartingWithA));
// ['Ada', 'and', 'at', 'all']
```

### Looking for a word (from Unicode characters)

Instead of the Latin alphabet, we can use a range of Unicode characters to identify a word (thus being able to deal with text in other languages like Russian or Arabic). The "Basic Multilingual Plane" of Unicode contains most of the characters used around the world and we can use character classes and ranges to match words written with those characters.

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

console.table(nonEnglishText.match(regexpBMPWord));
["Приключения", "Алисы", "в", "Стране", "чудес"];
```

### Counting vowels

```js
const aliceExcerpt =
  "There was a long silence after this, and Alice could only hear whispers now and then.";
const regexpVowels = /[AEIOUYaeiouy]/g;

console.log("Number of vowels:", aliceExcerpt.match(regexpVowels).length);
// Number of vowels: 26
```

See also
--------

* Regular expressions guide
* Assertions guide
* Quantifiers guide
* Groups and backreferences guide
* `RegExp`


Quantifiers - JavaScript

Quantifiers
===========

Quantifiers indicate numbers of characters or expressions to match.

Try it
------

Types
-----

**Note:** In the following, *item* refers not only to singular characters, but also includes character classes and groups and backreferences.

| Characters | Meaning |
| --- | --- |
| `*x**` |
 Matches the preceding item "x" 0 or more times. For example,
 `/bo*/` matches "boooo" in "A ghost booooed" and "b" in "A
 bird warbled", but nothing in "A goat grunted".
  |
| `*x*+` |
 Matches the preceding item "x" 1 or more times. Equivalent to
 `{1,}`. For example, `/a+/` matches the "a" in
 "candy" and all the "a"'s in "caaaaaaandy".
  |
| `*x*?` |
 Matches the preceding item "x" 0 or 1 times. For example,
 `/e?le?/` matches the "el" in "angel" and the "le" in
 "angle."

 If used immediately after any of the quantifiers `*`,
 `+`, `?`, or `{}`, makes the
 quantifier non-greedy (matching the minimum number of times), as
 opposed to the default, which is greedy (matching the maximum number
 of times).
  |
| `*x*{*n*}` |
 Where "n" is a positive integer, matches exactly "n" occurrences of
 the preceding item "x". For example, `/a{2}/` doesn't match
 the "a" in "candy", but it matches all of the "a"'s in "caandy", and
 the first two "a"'s in "caaandy".
  |
| `*x*{*n*,}` |
 Where "n" is a positive integer, matches at least "n" occurrences of
 the preceding item "x". For example, `/a{2,}/` doesn't
 match the "a" in "candy", but matches all of the a's in "caandy" and
 in "caaaaaaandy".
  |
| `*x*{*n*,*m*}` |
 Where "n" is 0 or a positive integer, "m" is a positive integer, and
 `*m* > *n*`, matches at least "n" and at most "m" occurrences of the preceding
 item "x". For example, `/a{1,3}/` matches nothing in
 "cndy", the "a" in "candy", the two "a"'s in "caandy", and the first
 three "a"'s in "caaaaaaandy". Notice that when matching "caaaaaaandy",
 the match is "aaa", even though the original string had more "a"s in
 it.
  |
| `*x**?``*x*+?``*x*??``*x*{n}?``*x*{n,}?``*x*{n,m}?` |
 By default quantifiers like `*` and `+` are
 "greedy", meaning that they try to match as much of the string as
 possible. The `?` character after the quantifier makes the
 quantifier "non-greedy": meaning that it will stop as soon as it finds
 a match. For example, given a string like "some <foo> <bar>
 new </bar> </foo> thing":
 * `/<.*>/` will match "<foo> <bar> new
 </bar> </foo>"
* `/<.*?>/` will match "<foo>"
 |

Examples
--------

### Repeated pattern

```js
const wordEndingWithAs = /\w+a+\b/;
const delicateMessage = "This is Spartaaaaaaa";

console.table(delicateMessage.match(wordEndingWithAs)); // [ "Spartaaaaaaa" ]
```

### Counting characters

```js
const singleLetterWord = /\b\w\b/g;
const notSoLongWord = /\b\w{2,6}\b/g;
const longWord = /\b\w{13,}\b/g;

const sentence = "Why do I have to learn multiplication table?";

console.table(sentence.match(singleLetterWord)); // ["I"]
console.table(sentence.match(notSoLongWord)); // [ "Why", "do", "have", "to", "learn", "table" ]
console.table(sentence.match(longWord)); // ["multiplication"]
```

### Optional character

```js
const britishText = "He asked his neighbour a favour.";
const americanText = "He asked his neighbor a favor.";

const regexpEnding = /\w+ou?r/g;
// \w+ One or several letters
// o followed by an "o",
// u? optionally followed by a "u"
// r followed by an "r"

console.table(britishText.match(regexpEnding));
// ["neighbour", "favour"]

console.table(americanText.match(regexpEnding));
// ["neighbor", "favor"]
```

### Greedy versus non-greedy

```js
const text = "I must be getting somewhere near the center of the earth.";
const greedyRegexp = /[\w ]+/;
// [\w ] a letter of the latin alphabet or a whitespace
// + one or several times

console.log(text.match(greedyRegexp)[0]);
// "I must be getting somewhere near the center of the earth"
// almost all of the text matches (leaves out the dot character)

const nonGreedyRegexp = /[\w ]+?/; // Notice the question mark
console.log(text.match(nonGreedyRegexp));
// "I"
// The match is the smallest one possible
```

See also
--------

* Regular expressions guide
* Character classes guide
* Assertions guide
* Groups and backreferences guide
* `RegExp`