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.

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

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

As you can see from the result,<br />

the exec() method places the entire matched string in element zero of the array and any<br />

substrings that match parenthesized subexpressions in subsequent elements.<br />

exec() and the Global Flag<br />

Sometimes you might wish to extract not just the first occurrence of a pattern in a string, but<br />

each occurrence of it. Adding the global flag (g) to a regular expression indicates the intent to<br />

search for every occurrence (i.e., globally) instead of just the first.<br />

<strong>The</strong> way the global flag is interpreted by RegExp and by String is a bit subtle. In RegExp, it‘s<br />

used to perform a global search incrementally, that is, by parsing out each successive<br />

occurrence of the pattern one at a time. In String, it‘s used to perform a global search all at<br />

once, that is, by parsing out all occurrences of the pattern in one single function call. We‘ll cover<br />

using the global flag with String methods in the following section.<br />

To demonstrate the difference between a regexp with the global flag set and one without,<br />

consider the following simple example:<br />

var lucky = "<strong>The</strong> lucky numbers are 3, 14, and 27";<br />

var pattern = /\d+/;<br />

document.writeln("Without global we get:");<br />

document.writeln(pattern.exec(lucky));<br />

document.writeln(pattern.exec(lucky));<br />

document.writeln(pattern.exec(lucky));<br />

pattern = /\d+/g;<br />

document.writeln("With global we get:");<br />

document.writeln(pattern.exec(lucky));<br />

document.writeln(pattern.exec(lucky));

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

Saved successfully!

Ooh no, something went wrong!