06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Data Structures and Manipulation<br />

The exec() method is useful in getting information about the match found because<br />

it returns an object with information about the match. The object returned from<br />

exec() has an index property that tells us where the successful match begins in the<br />

string. This is useful in many ways:<br />

var match = /\d+/.exec("There are 100 ways to do this");<br />

console.log(match);<br />

// ["100"]<br />

console.log(match.index);<br />

// 10<br />

Alternatives – OR<br />

Alternatives can be expressed using the | (pipe) character. For example, /a|b/<br />

matches either the a or b character, and /(ab)+|(cd)+/ matches one or more<br />

occurrences of either ab or cd.<br />

Beginning and end<br />

Frequently, we may wish to ensure that a pattern matches at the beginning of a<br />

string or perhaps at the end of a string. The caret character, when used as the first<br />

character of the RegEx, anchors the match at the beginning of the string such that<br />

/^test/ matches only if the test substring appears at the beginning of the string<br />

being matched. Similarly, the dollar sign ($) signifies that the pattern must appear at<br />

the end of the string: /test$/.<br />

Using both ^ and $ indicates that the specified pattern must encompass the entire<br />

candidate string: /^test$/.<br />

Backreferences<br />

After an expression is evaluated, each group is stored for later use. These values are<br />

known as backreferences. Backreferences are created and numbered by the order in<br />

which opening parenthesis characters are encountered going from left to right. You<br />

can think of backreferences as the portions of a string that are successfully matched<br />

against terms in the regular expression.<br />

The notation for a backreference is a backslash followed by the number of the<br />

capture to be referenced, beginning with 1, such as \1, \2, and so on.<br />

[ 84 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!