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 - Using regular expressions in JavaScript (Page 6 of 9 )
Using regular expressions in JavaScript is very easy, often being passed over by people who don�t know that it can be done, or by developers arguing that parsing regular expressions slows down client-side applications. Whatever the reasons are, let�s show how we can create a regular expression in JavaScript:
var re = /regexp/;
where regexp is the regular expression itself. Extending the concept to our first example presented in the basics section, let�s build one that detects the string �JavaScript�:
var re = /JavaScript/;
As default behavior, JavaScript regular expressions are case sensitive and only search for the first match in any given string. But we can add more functionality by adding the g and i modifiers (g for global and i for insensitive). Annexing the modifiers after the last /, we can make a regular expression search for all matches in the string and ignore case. Once again, let�s see some examples to properly understand these concepts.
Given the string �example1 Example2 EXAMPLE3�, the following regular expressions match as listed below:
/Example[0-9]+/ // Matches �Example2�
/Example[0-9]+/i // Matches �example1�
/Example[0-9]+/gi // Matches �example1�, �Example2� and �EXAMPLE3�
As seen in the previous examples, the use of �i� and �g� modifiers increases noticeably the matching capabilities of regular expressions. So don�t forget they exist when you code your next script.
Applying methods to JavaScript strings
Using a regular expression is easy. Every JavaScript variable containing a text string is able to support four main methods (in Object Oriented parlance) or functions to work with regular expressions. They are match(), replace(), search() and test(), the last one being an object method rather than a string method.