If you ve ever programmed in Perl, or have had to work as a Unix system administrator, then you probably already have more than a passing familiarity with regular expressions . In this article, I ll start out by explaining what, exactly, regular expressions are and what they can do for you. Finally, I ll finish off by explaining how regular expressions are used in JavaScript, with a practical example or two to help the concepts gel. For example, if you re presenting your visitors with an HTML form to enter their details, you might have one field for their phone number. Writing a script to check every character of the entered string to ensure that all the numbers are where they belong, with parentheses and a dash in just the right spots, would be a pretty tedious bit of code to write.
Regular expressions provide a quick and easy way of matching a string to a pattern.
In our phone number example, we could write a simple regular expression and use it to check in one quick step whether or not any given string is a properly formatted phone number. We ll explore this example a little further, once we ve taken care of a few technical details. Regular expressions can look fairly complex at times, but when it comes right down to it they re actually just text strings themselves. Any string containing the text JavaScript is said to match this regular expression. Thus, this regular expression allows us to detect strings containing this particular string of text.