Java Script
Pattern Matching Using Regular Expressions
Metacharacters
• Character class– [abc] matches ‘a’ or ‘b’ or ‘c’– [a-z] matches a through z– [^aeiou] matches any character except a vowel
• ^ - beginning of the string• $ - end of the string
Predefined Character ClassesName Equivalent Pattern Matches
\d [0-9] A digit
\D [^0-9] Not a digit
\w [A-Za-z_0-9] A word character (alphanumeric)
\W [^A-Za-z_0-9] Not a word character
\s [ \r\t\n\f] A whitespace character
\S [^ \r\t\n\f] Not a whitespace character
Matches
var matches = str.match(/^\d\.\d\d$/);matches 3.14
var matches = str.match(/^\w\w\w$/);var matches = str.match(/^\w{3}$/);
matches abc or 123 or Abc
* + Metacharacters
• * = zero or more• + = one or morevar matches = str.match(/^\d+\.\d*$/);
matches 123.45 or 123.
var matches = str.match(/^[A-Za-z]\w*$/);identifiers in programming languages
Social Security Number
if(!document.forms[0].mySSN.value.match(/^\d{3}-\d{2}-\d{4}$/);
{alert(“Invalid ssn.”); return false;}
^ = beginning of string$ = end of string
? Metacharacter
Parse Zip Code
var zipcode = str.match(/^\d{5}(-\d{4})?$/);
date
If(str.match(/^1?\d\/\d?\d\/\d\d$/) == null){
alert(“invalid date”);}
? = zero or one
Trim
• date = date.trim();