Book Image

Javascript Regular Expressions

By : Loiane Groner, Gabriel Manricks
Book Image

Javascript Regular Expressions

By: Loiane Groner, Gabriel Manricks

Overview of this book

This book is ideal for JavaScript developers and programmers who work with any type of user entry data and want sharpen their skills to become experts.
Table of Contents (8 chapters)

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