JavaScript Regular Expressions and Exec()

JavaScript’s regular expressions method exec() is a great way to break apart a string into components you may need.

Given an expression, such as /(\([\d]{3}\)) ([\d]{3})-([\d]{4})/, you can use this for more than verifying that a string contains the pattern that matches a pattern like (xxx) xxx-xxxx where x is a number. You can use exec() to determine what the contents are for each of the 3 grouped elements of the screen. The () in the pattern identifies the grouping. Notice that grouping of \([\d]{3}\), [\d]{3} and [\d]{4} in the previous pattern. This pattern could be used to identify the contents of each group by using the following code:


    /* given a string */
    var str = "(408) 555-1212" ;

    /* given a pattern */
    var re = /(\([\d]{3}\)) ([\d]{3})-([\d]{4})/ ; 

    /* execute the pattern against the str */
    var match = str.exec(re) ;

    /* retrieve the values in each of the pattern positions */
    /* match[1]  is the first group  and returns (408) */
    /* match[2]  is the second group and returns 555  */
    /* match[3]  is the third group  and returns 1212 */
    /* match.index gives the 0-based index into the input string, identifying 
       where the pattern starts ... since it may not always start at the 
       beginning of the string */
    /* match.input returns the original string being examined  */

You may have as many groups as you like in the pattern, and the returned array will have one entry for each of the groups. If you pattern indicates that one group may have zero characters returned and there are zero characters found for that position, the match will return a “” string.

This works well in place of str.indexOf(), str.search(), str.contains(), str.substr() and many of there JavaScript methods you might otherwise use.

Leave a Reply