Skip to main content

JavaScript Regular Expressions

JavaScript Regex Quantifiers

Written by Published

Quantifiers say how many times a pattern should repeat.

Without one, a pattern matches exactly one character.

Quantifiers turn that into one or more, none or more, or an exact count.

Example

Example

javascript

console.log(/\d+/.test("abc"));
console.log("room 42".match(/\d+/)[0]);

+ matched both digits together, giving 42.

The Quantifiers

+ one or more, * none or more.

? none or one, making it optional.

{2} exactly two, {2,4} between two and four.

Syntax

Syntax

javascript

/\d+/     // one or more digits
/\d{3}/   // exactly three

A quantifier applies to whatever is directly before it.

One or More

+ is the one you will use most.

Example

Example

javascript

const text = "a1 bb22 ccc333";

console.log(text.match(/\d+/g).join(","));
console.log(text.match(/[a-z]+/g).join(","));

Each run of characters is grouped into one match.

Optional Characters

? makes the previous item optional.

Example

Example

javascript

console.log(/colou?r/.test("color"));
console.log(/colou?r/.test("colour"));
console.log(/colou?r/.test("colouur"));

The output is true, true, false.

An Exact Count

Curly braces are ideal for fixed-length codes.

Example

Example

javascript

console.log(/^\d{4}$/.test("2026"));
console.log(/^\d{4}$/.test("202"));
console.log(/^\d{2,4}$/.test("202"));

The output is true, false, true.

Greedy Matching

By default a quantifier takes as much as it can.

This surprises people when matching tags or quotes.

Example

Example

javascript

const text = "<a><b>";

console.log(text.match(/<.+>/)[0]);
console.log(text.match(/<.+?>/)[0]);

The first took everything; the second stopped at the first closing bracket.

Lazy Matching

Adding ? after a quantifier makes it take as little as possible.

Example

Example

javascript

const text = "aaa";

console.log(text.match(/a+/)[0].length);
console.log(text.match(/a+?/)[0].length);

The output is 3 then 1.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Regex Quantifiers</title>
</head>
<body>

  <h1>Regex Quantifiers</h1>

  <p id="out"></p>

  <script>
    const text = "Order 12 shipped on 2026-01-15";

    document.getElementById("out").innerHTML =
      "All numbers: " + text.match(/\d+/g).join(", ") +
      "<br>Four digit year: " + text.match(/\d{4}/)[0] +
      "<br>Is 2026 a valid year: " + /^\d{4}$/.test("2026");
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try an exact count:

Change \d+ to \d{2} and compare the matches.

Important Points

  • + means one or more.
  • * means none or more.
  • ? makes something optional.
  • {n} matches an exact count.
  • Quantifiers are greedy unless you add ?.

Conclusion

Quantifiers are what make a pattern flexible.

Greedy matching is the behaviour that most often surprises people.

A lazy quantifier is usually the fix.