18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Regular Expressions<br />

Code Equal To Matches<br />

\S [^\t\n\x0B\f\r] A non-white–space character<br />

\w [a-zA-Z_0-9] A word character (all letters, all numbers, and an underscore)<br />

\W [^a-zA-Z_0-9] A non-word character<br />

Using predefined classes can make pattern matching significantly easier. Suppose you want to match<br />

three numbers, without using \d. Your code looks like this:<br />

var sToMatch = “567 9838 abc”;<br />

var reThreeNums = /[0-9][0-9][0-9]/;<br />

alert(reThreeNums.test(sToMatch)); //outputs “true”<br />

Using \d, the regular expression becomes much cleaner:<br />

var sToMatch = “567 9838 abc”;<br />

var reThreeNums = /\d\d\d/;<br />

alert(reThreeNums.test(sToMatch)); //outputs “true”<br />

Quantifiers<br />

Quantifiers enable you to specify how many times a particular pattern should occur. You can specify<br />

both hard values (for example, this character should appear three times) and soft values (for example,<br />

this character should appear at least once but can repeat any number of times) when setting how many<br />

times a pattern should occur.<br />

Simple quantifiers<br />

The following table lists the various ways to quantify a particular pattern.<br />

Code<br />

Description<br />

? Either zero or one occurrence<br />

* Zero or more occurrences<br />

+ One or more occurrences<br />

{n}<br />

{n,m}<br />

{n,}<br />

Exactly n occurrences<br />

At least n but no more than m occurrences<br />

At least n occurrences<br />

<strong>For</strong> example, suppose you want to match words bread, read, or red. Using the question mark quantifier,<br />

you can create just one regular expression to match all three:<br />

var reBreadReadOrRed = /b?rea?d/;<br />

201

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

Saved successfully!

Ooh no, something went wrong!