Defining nongreedy quantifiers
In the previous section, we had a look at multipliers, where you can specify that a pattern should be repeated a certain number of times. By default, JavaScript will try and match the largest number of characters possible, which means that it will be a greedy match. Let's say we have a pattern similar to /\d{1,4}/
that will match any text and has between one and four numbers. By default, if we use 124582948
, it will return 1245
, as it will take the maximum number of options (greedy approach). However, if we want, we can add the (?
) question mark operator to tell JavaScript not to use greedy matching and instead return the minimum number of characters as possible:
Greedy matching is something that makes it difficult to find bugs in your code. Consider the following example text:
<div class="container" id="main"> Site content <div>
If we wanted to extract the class, you might think of writing a pattern in this way:
/class...