06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Data Structures and Manipulation<br />

In the following example, we create a pattern where the character u is optional (has 0<br />

or 1 occurrence):<br />

var str = /behaviou?r/;<br />

console.log(str.test("behaviour"));<br />

// true<br />

console.log(str.test("behavior"));<br />

// true<br />

It helps to read the /behaviou?r/ expression as 0 or 1 occurrences of character u.<br />

The repetition quantifier succeeds the character that we want to repeat. Let's try out<br />

some more examples:<br />

console.log(/'\d+'/.test("'123'")); // true<br />

You should read and interpret the \d+ expression as ' is a literal character match, \d<br />

matches characters [0-9], the + quantifier will allow one or more occurrences, and '<br />

is a literal character match.<br />

You can also group character expressions using (). Observe the following example:<br />

var heartyLaugh = /Ha+(Ha+)+/i;<br />

console.log(heartyLaugh.test("HaHaHaHaHaHaHaaaaaaaaaaa"));<br />

//true<br />

Let's break the preceding expression into smaller chunks to understand what is<br />

going on in here:<br />

• H: literal character match<br />

• a+: 1 or more occurrences of character a<br />

• (: start of the expression group<br />

• H: literal character match<br />

• a+: 1 or more occurrences of character a<br />

• ): end of expression group<br />

• +: 1 or more occurrences of expression group (Ha+)<br />

Now it is easier to see how the grouping is done. If we have to interpret the<br />

expression, it is sometimes helpful to read out the expression, as shown in the<br />

preceding example.<br />

[ 82 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!