Tutorial List
Home
Interview Questions
Interview
Interview Questions
Links
Web Home
About Us

JS Regular Expression


Regular Expression Syntax
Regular Expression is used to identify, test or validate some pattern. It is extreamly useful in form validation. It required only 20% code for form validation as compare to conventional method.
Lets See how JS regular expression works,
^ : Start regular expression
$ : End regular expression
? : Zero or one occurrences of the preceding character
+ : one or more occurrences of the preceding character
* : Zero or more occurrences of the preceding character
\. : Represents any character except a newline
\d : Represents any digit [0,9]
\D : Represents any character
\w : Represents any word character(letters, digits and underscore)
\W : Represents any character except word character
\s : Represents any white-space character (space, tab and new line)
\S : Represents any non white-space character
^ : Used for negating expression (Don't get confused with start char)
[] : Used for grouping the chars
Sample:
var re = /^\w{6,15}$/;                        // word chars with size [6,15]
var name = /^[a-zA-Z]{1,500}$/;       // only albhabets upto 500 max length eg. Chennai
var modelNum = /^[a-zA-Z0-9]+$/;   // String containing any lower, uppar case letter and digit
var compName = /^((\w+\.?)\s?(\w+\.?))+$/;     // eg 'Mars Informations Solutions'
var phoneNumber = /^\d{10}$/;   // A phone number with exactly 10 digit 9999999999
var zip = /^\d{6}$/;                      // 666666
var warranty = /^\d{1,3}$/;          // A integer number with range [0-999]
How to use regular expression:
Just create a normal js varible by assigning regular expression as string(see in sample).
Call test(arg) on regular expression variable where arg is pattern to be tested.
if pattern passes the regular expression, then test(arg) returns true else returns false
Example:
if(!phoneNumber.test('9252963450'))
{
alert("Given phone number is not valid");
} else{
alert("Given phone number is valid");
}

No comments: