Monday, November 21, 2005

JavaScript RegExp Object - Using Regular Expressions with Client Side Scripting

JavaScript RegExp Object - Using Regular Expressions with Client Side Scripting: "If you use JavaScript to validate user input on a web page at the client side, using JavaScript's regular expression support will greatly reduce the amount of code you need to write.

In JavaScript, a regular expression is written in the form of /pattern/modifiers where 'pattern' is the regular expression itself, and 'modifiers' are a series of characters indicating various options. The 'modifiers' part is optional. This syntax is borrowed from Perl. JavaScript supports the following modifiers, a subset of those supported by Perl:

* /g enables 'global' matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.
* /i makes the regex match case insensitive.
* /m enables 'multi-line mode'. In this mode, the caret and dollar match before and after newlines in the subject string.

You can combine multiple modifiers by stringing them together as in /regex/ism.

Since forward slashes delimit the regular expression, any forward slashes that appear in the regex need to be escaped. E.g. the regex 1/2 is written as /1\/2/ in JavaScript.
Regexp Methods of The String Class

To test if a particular regex matches (part of) a string, you can call the strings's match() method: if (myString.match("