Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Javascript Regular Expressions

You're reading from   Javascript Regular Expressions Leverage the power of regular expressions to create an engaging user experience

Arrow left icon
Product type Paperback
Published in May 2015
Publisher
ISBN-13 9781783282258
Length 112 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

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:

Defining nongreedy quantifiers

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...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image