11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Table 8-2: Regular Expression Escape Codes<br />

Code Matches<br />

>\uHHHH<br />

Unicode<br />

character<br />

represented<br />

by the<br />

hexadecimal<br />

value HHHH<br />

>\cX<br />

Control<br />

character<br />

represented<br />

by ^X, for<br />

example,<br />

\cH<br />

represents<br />

CTRL-H<br />

Unicode character represented by the hexadecimal value HHHH<br />

Control character represented by ^X, for example, \cH represents CTRL-H<br />

Using the appropriate escape code, we can now define a regular expression that matches<br />

―http://www.w3c.org/‖ (and any other string containing it):<br />

var pattern = /http:\/\/www\.w3c\.org\//;<br />

Because / has special meaning in regular expression literals (it means the beginning or end of<br />

the pattern), all the forward slashes (/) in the pattern are replaced with their escaped equivalent,<br />

\/.<br />

<strong>The</strong> important thing to remember is that whenever you want to include a character in a pattern<br />

that has a special regexp meaning, you must use its escape code instead.<br />

Repetition Quantifiers<br />

Regular expression repetition quantifiers allow you to specify the number of times a particular<br />

item in the expression can or must be repeated. For now, consider that by ―particular item‖ we<br />

mean ―previous character.‖ <strong>The</strong> distinction will become clear later in the chapter. As an<br />

example of a repetition quantifier, * (the asterisk) indicates that the previous item may occur<br />

zero or more times. Any sequence of zero or more repetitions of the previous item can be<br />

present in the strings the pattern will match. For example:<br />

var pattern = /ab*c/;<br />

Read the * as ―repeated zero or more times.‖ Doing so, we read this pattern as matching any<br />

string containing an ―a‖ that is followed immediately by ―b‖ repeated zero or more times,<br />

followed immediately by a ―c.‖ All the following strings will match this expression:<br />

ac<br />

abc<br />

abbbbbbbbbbbbbbbbbbbbbbbbbbbc<br />

<strong>The</strong> letters abc begin the alphabet<br />

Similarly, + specifies that the previous character must be repeated one or more times. <strong>The</strong><br />

following declaration

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

Saved successfully!

Ooh no, something went wrong!