Searching with Regular Expressions


zip.test("Indianapolis, IN 46240"); 

Defining a regular expression in JavaScript can be done in two ways:

  • var zip = new RegEx("\\d{5}");

  • var zip = /\d{5}/;

There is no functional difference between the two approaches; you just have to take character escaping into account. Then, the test() method of the expression checks whether a string contains the regular expression:

var found = zip.test("Indianapolis, IN 46240"); //true 


If you are interested in the actual match, use the exec() function. The method returns an array. Its first array element is the whole match, and the next elements are all submatches (if parentheses are used in the regular expression).

var matches = zip.exec("Indianapolis, IN 46240"); // ["46240"] 


Tip

The method match() returns all matches; exec() returns only the current match, usually the first one. However, if you call exec() multiple times, all matches are returned.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net