JavaScript / ECMAScript

Lazy / Non-Greedy Quantifier in JS

Demonstrate lazy quantifiers `+?` by matching the SHORTEST HTML-like tag rather than the longest greedy span.

Try it in the JS tester →

Pattern

regexJS
<.+?>   (flags: g)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("<.+?>", "g");
const input = "<b>bold</b> and <i>italic</i>";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

<.+?> matches an opening `<`, then ONE OR MORE characters (`.+`), then the next `>`. The `?` after `+` makes the quantifier lazy — it stops at the first `>` it sees, instead of the greedy default that would consume everything up to the LAST `>` in the string.

Examples

Input

<b>bold</b> and <i>italic</i>

Matches

  • <b>
  • </b>
  • <i>
  • </i>

Input

<div class="foo">x</div>

Matches

  • <div class="foo">
  • </div>

Input

no tags

No match

Same pattern, other engines

← Back to Lazy / Non-Greedy Quantifier overview (all engines)