O'Reilly logo

JavaScript Regular Expressions by Gabriel Manricks, Loiane Groner

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required