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

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

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

and contains any special flags for that expression. <strong>The</strong> two previous examples could<br />

equivalently be declared as<br />

var pattern = new RegExp("http");<br />

var patternIgnoringCase = new RegExp("http", "i");<br />

<strong>The</strong> constructor syntax is most commonly used when the pattern to match against is not<br />

determined until runtime. You might allow the user to enter a regular expression and then pass<br />

the string containing that expression to the RegExp() constructor.<br />

<strong>The</strong> most basic method provided by the RegExp object is test(). This method returns a<br />

Boolean indicating whether the string given as its argument matches the pattern. For example,<br />

we could test<br />

var pattern = new RegExp("http");<br />

pattern.test("HTTP://WWW.W3C.ORG/");<br />

which returns false because pattern matches only strings containing ―http.‖ Or we could test<br />

using the case-insensitive pattern,<br />

var patternIgnoringCase = new RegExp("http", "i");<br />

patternIgnoringCase.test("HTTP://WWW.W3C.ORG/");<br />

which returns true because it matches for strings containing ―http‖ while ignoring case. Of<br />

course, you won't see much unless you use the returned value:<br />

var patternIgnoringCase = new RegExp("http", "i");<br />

alert(patternIgnoringCase.test("HTTP://WWW.W3C.ORG/"));<br />

Because of <strong>JavaScript</strong>'s automatic type conversion, you can invoke RegExp methods on<br />

regular expression literals (just like String methods on string literals). For example,<br />

alert(/http/i.test("HTTP://WWW.W3C.ORG/"));<br />

would alert out true as well.<br />

Creating Patterns<br />

<strong>The</strong> example patterns so far merely check for the presence of a particular substring; they<br />

exhibit none of the powerful capabilities to which we have alluded. Regular expressions use<br />

special character sequences enabling the programmer to create more complicated patterns.<br />

For example, special characters provide a way to indicate that a certain character or set of<br />

characters should be repeated a certain number of times or that the string must not contain a<br />

certain character.<br />

Positional Indicators<br />

<strong>The</strong> first set of special characters can be thought of as positional indicators, characters that<br />

mandate the required position of the pattern in the strings against which it will be matched.

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

Saved successfully!

Ooh no, something went wrong!