Regular expressions and form handling

Objectives

  • Use regular expressions in JavaScript
  • Use special characters in regular expressions
  • Use character classes in regular expressions
  • Specify grouping in regular expressions
  • Specify repetition in regular expressions
  • Use the String class regular expression methods
  • Use regular expression (RegExp) objects

Validating an email

The following regular expression is sometimes used to validate emails:

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

  • The ^ at the start prevents anything from being in front of what we match.
  • The $ at the end prevents anything from being after what we match.
  • \w stands for any letter, digit, or underscore
  • \w+ stands for one or more letters, digits, and underscores
  • [\.-] stands for either a period or a -
  • [\.-]? stands for there might be one period or one -, or there might be none
  • [\.-]?\w+ will match a string that might or might not start with a period or a dash, followed by one or more letters, digits, and underscores
  • ([\.-]?\w+)* will match zero or more of the item in parentheses; this means that it might not be present at all, or there may be one or more occurrences of the pattern
  • (\.\w{2,3}) will match a period followed by two or three letters, digits, and underscores

See form10.html for an example which uses this regular expression to validate email addresses.

Replacing parts of a string

This example changes names from "first name, last name" order to "last name, first name" order. The example given here also reverses the names, but includes a sort, and does it with a little less JavaScript. See RegEx1.html for an online example.

Using the RegExp object (and adding functionality to built-in classes)

This example is similar to the last example, but includes some code to convert each name to proper case. In this example, only the first letters of names are converted to upper case. This example also demonstrates how a new function can be added to a built-in class. This example differs significantly from the example in the text. See RegEx2.html for an online example. Note also that computers will go ahead and mess up names like DeKalb and O'Malley that don't follow the rules that were programmed (because they have capital letters other than the first letter).