Regular Expressions
About Regular Expressions

Regular expression specifies a pattern of characters and we can match strings with this pattern. Regular expression were introduced in Javascript 1.2 with RegExp Object.

Generally we use regular expression for valiting form.
like
valid email address
10 digit numeric mobile number
URL of the website
etc.

How to create regular expression object

Regular expression can declared using RegExp() constructor. This first argument is pattern and second argument is any special flags for that expression(second argument is optional)

Example:-
var pattern=new RegExp("https");
var pattern=new RegExp("https","i");

How to check regular expression

RegExp object provide test function. test functions return boolean means true/false.

Example 1:-
<script language="javascript" type="text/javascript">
var pattern=new RegExp("www");
document.write(pattern.test("www.test.com"));
</script>

Output:-
true

Note:- test function check pattern www in string(www.test.com).
here www contain in string so this return true.

Example 2:-
<script language="javascript" type="text/javascript">
var pattern=new RegExp("www");
document.write(pattern.test("http://test.com"));
</script>

Output:-
false

Note:- test function check pattern www in string(www.test.com).
here www does not contain in string so this return false.


Regular expression notation

[0-9] =  Any one digit between 0 to 9 like 6
[a-z] = Any alphabetic character a to z like m
[A-Z] = Any alphabetic character A to Z like M
[^0-5] = Any one digit between 0-5 like 4
[^a-z] = Any alphabetic character A to Z like M
[^A-Z] = Any alphabetic character a to z like m
. = Any character except newline.
w = Any word character
W = Any non-word character
d = same as [0-9]
D = same as [^0-9]
n$ = match string at the end like is$
^n= match string at the beginning  like ^ITC

Example to explain regular expression

<html>
<head>
<title>Javascript example</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var pattern1=new RegExp(/[0-9]/);
var pattern2=new RegExp(/[0-9]{3}/);
var pattern3=new RegExp(/[a-z]/);
var pattern4=new RegExp(/[a-z]{4}/);
var pattern5=new RegExp(/[a-zA-Z0-9]/);
var pattern6=new RegExp(/[0-9]{3}-[0-9]{4}/);

document.write(pattern1.test("8")+"<br>");
document.write(pattern2.test("889")+"<br>");
document.write(pattern3.test("s")+"<br>");
document.write(pattern4.test("sunday")+"<br>");
document.write(pattern5.test("R")+"<br>");
document.write(pattern6.test("768-3989")+"<br>");
</script>
</body>
</html>


Previous
Next