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 />

One critical variation of this pattern is a range of values. If we want to match against<br />

a sequential range of characters or numbers, we can use the following pattern:<br />

var pattern = /[0-5]/;<br />

console.log(pattern.test(3)); //true<br />

console.log(pattern.test(12345)); //true<br />

console.log(pattern.test(9)); //false<br />

console.log(pattern.test(6789)); //false<br />

console.log(/[0123456789]/.test("This is year 2015")); //true<br />

Special characters such as $ and period (.) characters either represent matches to<br />

something other than themselves or operators that qualify the preceding term. In<br />

fact, we've already seen how [, ], -, and ^ characters are used to represent something<br />

other than their literal values.<br />

How do we specify that we want to match a literal [ or $ or ^ or some other special<br />

character? Within a RegEx, the backslash character escapes whatever character<br />

follows it, making it a literal match term. So \[ specifies a literal match to the [<br />

character rather than the opening of a character class expression. A double backslash<br />

(\\) matches a single backslash.<br />

In the preceding examples, we saw the test() method that returns true or false<br />

based on the pattern matched. There are times when you want to access occurrences<br />

of a particular pattern. The exec() method comes in handy in such situations.<br />

The exec() method takes a string as an argument and returns an array containing all<br />

matches. Consider the following example:<br />

var strToMatch = 'A Toyota! Race fast, safe car! A Toyota!';<br />

var regExAt = /Toy/;<br />

var arrMatches = regExAt.exec(strToMatch);<br />

console.log(arrMatches);<br />

The output of this snippet would be ['Toy']; if you want all the instances of the<br />

pattern Toy, you can use the g (global) flag as follows:<br />

var strToMatch = 'A Toyota! Race fast, safe car! A Toyota!';<br />

var regExAt = /Toy/g;<br />

var arrMatches = regExAt.exec(strToMatch);<br />

console.log(arrMatches);<br />

[ 78 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!