JavaScript is useful for a lot more than opening pop-ups. If you use HTML forms on your website, and want to make sure that your visitors submit valid data on those forms, you might want to consider using some regular expressions in JavaScript. Alejandro Gervasio explains how, with many excellent examples.
Regular expressions in JavaScript - Counted Subexpressions (Page 5 of 9 )
We can specify how many times something can be repeated by using a numerical expression in curly braces ({ }). We can define an exact number of repetitions ({3} means exactly 3 repetitions), a range of repetitions ({2,4} means from 2 to 4 repetitions), or an open-ended range of repetitions ({2,} means at least two repetitions).
For example,
computer{1,3} // Matches �computer�, �computer computer� and �computer computer computer�.
Branching
Another useful option in building regular expressions is to represent choices for a string. This is done with a vertical pipe (|).
For example, if we want to match several domains, such as com, edu or net, the following expression would be used:
( com)|(edu)|(net)
Summary of special characters
Here are a few special characters that can be used for matching characters in regular expressions:
\n // a newline character
. // any character except a newline
\r // a carriage return character
\t // a tab character
\b // a word boundary (the start or end of a word)
\B // anything but a word boundary.
\d // any digit (same as [0-9])
\D // anything but a digit (same as [^0-9])
\s // single whitespace (space, tab, newline, etc.)
\S // single nonwhitespace.
\w // A �word character� (same as [0-9a-zA-Z_])
\W // A �nonword character (same as [^0-9a-zA-Z_]
Of course, there are more special characters and tips for regular expressions, generally well covered in any complete reference. For the sake of brevity, this list is good enough for this article. Since JavaScript has the same support that Perl for regular expressions, any full guide focused on Perl regular expressions will be applicable to JavaScript too.
Now, with all of the basics covered, we�ll see how we can add the power of regular expressions to our JavaScript code, making our developer life a lot easier and expanding our background a little bit more.