Friday, 4 May 2012

JavaScript Regular Expression

A regular expression is really just a sequence of characters that specify a pattern to be matched against a string of text when performing searches and replacements. A simple regular expression consists of a character or set of characters that matches itself.

JavaScript regular expressions are used primarily to verify data input on the client side.

Checking the form on the client side allows for instant feedback, and less traveling back and forth between the browser and server. The ability to check for any type of input, such as e-mail addresses, passwords, Social Security numbers, and birthdates is greatly simplified.

The Constructor Method

The constructor method, called RegExp(), creates a RegExp object. The RegExp() constructor
takes one or two arguments. The first argument is the regular expression; it is a
string representing the regular expression, for example, “blue” represents the literal
regular expression /blue/. The second optional argument is called a flag such as i for
case insensitivity or g for global. The constructor method is used when the regular
expression is being provided from some other place, such as from user input, and can
change throughout the run of the program. This method is handled at runtime.

Options Used for Modifying Search Patterns

Option Purpose
i              Used to ignore case.
g             Used to match for all occurrences of the pattern in the string.
m            Used to match over multiple lines.
FORM
Syntax
var variablename = /regular expression/options;

Example
var myregexp = /freedom/;
var reobjexp = /Samuel/ig;

Syntax
var variablename = new RegExp("regular expression", "options");

Example
var myreg = new RegExp("Freedom");
var reobj = new RegExp("Samuel", "ig");

RegExp Object
The RegExp object has two methods that can be used to test for a match in a string,
the test() method and the exec() method, which are quite similar.

test() Method Tests for a match in a string and returns either true or false.

Example
var string="String to be tested comes here ";
var regex = /regular expression/; // Literal way
var regex=new RegExp("regular expression"); // Constructor way
regex.test(string); // Returns either true or false

or
/regular expression/.test("string");

FORMAT
exec() Method Executes a search for a match in a string and returns an array.

Example
array = regularexpression.exec(string);
or
list = /ring/.exec("This is a test string collection");

No comments:

Post a Comment