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.

also repeatedly apply this method to a string in order to step through the portions of the string<br />

that match, one by one.<br />

<strong>The</strong> exec() method accepts a string to match against, and it can be written shorthand by<br />

directly invoking the name of the regexp as a function. For example, the two invocations in the<br />

following example are equivalent:<br />

var pattern = /http:.*/;pattern.exec("http://www.w3c.org/");pattern("http://www.w3c.org/");<br />

<strong>The</strong> exec() method returns an array with a variety of properties. Included are the length of the<br />

array; input, which shows the original input string; index, which holds the character index at<br />

which the matching portion of the string begins; and lastIndex, which points to the character<br />

after the match, which is also where the next search will begin. <strong>The</strong> script here illustrates the<br />

exec() method and its returned values:<br />

var pattern = /cat/;var result = pattern.exec("He is a big cat, a fat black cat named Rufus.");<br />

document.writeln("result = "+result+"");<br />

document.writeln("result.length = "+result.length+"");<br />

document.writeln("result.index = "+result.index+"");<br />

document.writeln("result.lastIndex = "+result.lastIndex+"");<br />

document.writeln("result.input = "+result.input+"");<br />

<strong>The</strong> result of this example is shown here:<br />

<strong>The</strong> array returned may have more than one element if subexpressions are used. For example,<br />

the following script has a set of three parenthesized subexpressions that are parsed out in the<br />

array separately:<br />

var pattern = /(cat) (and) (dog) /;<br />

var result = pattern.exec("My cat and dog are black.");<br />

document.writeln("result = "+result);<br />

document.writeln("result.length = "+result.length);<br />

document.writeln("result.index = "+result.index);

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

Saved successfully!

Ooh no, something went wrong!