Defining a regular expression in JavaScript can be done in two ways:
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. |