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.

}<br />

}<br />

}<br />

// Return false if there's not<br />

if (phone.charAt(i) != "-")<br />

return false;<br />

// Else there should be a digit here...<br />

else<br />

{<br />

}<br />

// Return false if there's not<br />

if (!isDigit(phone.charAt(i)))<br />

return true;<br />

return false;<br />

This is a lot of code for such a seemingly simple task. <strong>The</strong> code is far from elegant, and just<br />

imagine how much more complicated it would have to be if you wanted to validate other<br />

formats—for example, phone numbers with extensions, international numbers, or numbers with<br />

the dashes or area code omitted.<br />

Regular expressions simplify tasks like this considerably by allowing programmers to specify a<br />

pattern against which a string is ―matched.‖ This frees developers from having to write<br />

complicated and error-prone text matching code like we did in the preceding example. But<br />

regular expressions are not just limited to determining whether a string matches a particular<br />

pattern (like our NNN-NNN-NNNN in the preceeding listing); if the string does match, it is<br />

possible to locate, extract, or even replace the matching portions. This vastly simplifies the<br />

recognition and extraction of structured data like URLs, e-mail addresses, phone numbers, and<br />

cookies. Just about any type of string data with a predictable format can be operated upon with<br />

regular expressions.<br />

<strong>The</strong> Concept of Regular Expressions<br />

A regular expression specifies a pattern of characters. You can, for example, specify a pattern<br />

like we saw for data like a North American phone number that has three digits followed by a<br />

dash followed by three digits followed by a dash and four more digits. Because regular

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

Saved successfully!

Ooh no, something went wrong!