Regex Capture Groups with JavaScript Examples

Extract parts of text using numbered and named capture groups.

Why this matters

Use noncapturing groups (?:...) for grouping without extraction; use named groups for readability.

Worked example

Start with this sample input:

Order #4821

Example result or interpretation (check the linked tool for exact formatting):

Order #(?<id>\d+)

The named group id captures 4821; the complete match is Order #4821.

A match and a capture are different

The complete match includes everything consumed by the pattern. Capturing groups extract selected portions. Named groups make downstream code less dependent on group order.

JavaScript extraction examples

Named group

/Order #(?<id>\d+)/.exec("Order #4821")?.groups?.id

Interpretation: 4821

Noncapturing group

/(?:cat|dog) (\d+)/.exec("dog 3")?.[1]

Interpretation: 3

No match

/Order #(\d+)/.exec("Order #ABC")

Interpretation: null

Regular expressions are not a substitute for a parser when the input language has nested structures or complex escaping.

Step-by-step workflow

  1. Paste a sample string into Regex Playground.
  2. Enter the pattern and inspect the highlighted match.
  3. Check each capture group and test cases that should not match.

Try the related ByteKitly tool →

Common mistakes and limitations

A greedy .* can swallow more text than intended; test multiple examples and edge cases.

Test examples using your own data format and verify results before using them in production systems. ByteKitly's core converters operate in the browser, but avoid sharing confidential input in screenshots or links.

Continue learning

Browse all developer guides or explore all ByteKitly tools.