04.11.2015 Views

javascript

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

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

Chapter 5: Reference Types<br />

matches = pattern2.exec(text);<br />

alert(matches.index); //5<br />

alert(matches[0]);<br />

//bat<br />

alert(pattern2.lastIndex); //8<br />

The first pattern in this example, pattern1 , is not global, so each call to exec() returns the first match<br />

only ( “ cat “ ). The second pattern, pattern2 , is global, so each call to exec() returns the next match in<br />

the string until the end of the string has been reached. Note also how the pattern ’ s lastIndex property<br />

is affected. In global matching mode, lastIndex is incremented after each call to exec() , but it remains<br />

unchanged in nonglobal mode.<br />

A deviation in the IE implementation of JavaScript causes lastIndex to always be<br />

updated, even in nonglobal mode.<br />

Another method of regular expressions is test() , which accepts a string argument and returns true if<br />

the pattern matches the argument, and false if it does not. This method is useful when you want to<br />

know if a pattern is matched but you have no need for the actual matched text. The test() method is<br />

often used in if statements, such as the following:<br />

var text = “000-00-0000”;<br />

var pattern = /\d{3}\-\d{2}-\d{4}/;<br />

if (pattern.test(text)){<br />

alert(“The pattern was matched.”);<br />

}<br />

In this example, the regular expression tests for a specific numeric sequence. If the input text matches the<br />

pattern, then a message is displayed. This functionality is often used for validating user input, when you<br />

care only if the input is valid, not necessarily why it ’ s invalid.<br />

The inherited methods of toLocaleString() and toString() each return the literal representation of<br />

the regular expression, regardless of how it was created. Consider this example:<br />

var pattern = new RegExp(“\\[bc\\]at”, “gi”);<br />

alert(pattern.toString());<br />

// /\[bc\]at/gi<br />

alert(pattern.toLocaleString()); // /\[bc\]at/gi<br />

Even though the pattern in this example is created using the RegExp constructor, the<br />

toLocaleString() and toString() methods return the pattern as if it were specified in literal format.<br />

The valueOf() method for a regular expression returns the regular expression itself.<br />

This oddity occurs partially because the specification does not indicate what value<br />

should be returned by this method.<br />

119

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

Saved successfully!

Ooh no, something went wrong!