Web Programming Step by Step

Lecture XX
Client-Side Validation

Except where otherwise noted, the contents of this presentation are Copyright 2010 Marty Stepp and Jessica Miller.

Valid XHTML 1.1 Valid CSS!

Regular expressions in JavaScript

Replacing text with regular expressions

  • string.replace(regex, "text")
    • replaces the first occurrence of given pattern with the given text
    • var str = "Marty Stepp";
      str.replace(/[a-z]/, "x") returns "Mxrty Stepp"
    • returns the modified string as its result; must be stored
      str = str.replace(/[a-z]/, "x")
  • a g can be placed after the regex for a global match (replace all occurrences)
    • str.replace(/[a-z]/g, "x") returns "Mxxxx Sxxxx"
  • using a regex as a filter
    • str = str.replace(/[^A-Z]+/g, "") turns str into "MS"