Regular Expressions
9/21/2022 1
Regular Expressions
A regular expression is a sequence or pattern of
characters that specifies a rule.
Regular expressions are used to do pattern matching,
which is used in form validation.
2 ways to create regular expression in javascript
Using literal
var reExample = /pattern/;
Using the RegExp() constructor
var reExample = new RegExp("pattern");
9/21/2022 2
Regular expression methods
Exec()
Test()
String methods which use
regular expressions
Match()
Search()
Replace()
Split()
9/21/2022 3
The exec() Method
The exec() method takes one argument, a string, and
checks whether that string contains one or more
matches of the pattern specified by the regular
expression.
If one or more matches is found, the method returns a
result array with the starting points of the matches.
If no match is found, the method returns null.
9/21/2022 4
Test method()
The test() method also takes one argument, a string,
and checks whether that string contains a match of the
pattern specified by the regular expression.
It returns true if it does contain a match and false if it
does not.
var reexp = /^\d+$/;
reexp.test(“1234567”);
9/21/2022 5
<html>
<body>
<p>Do a global search, and test for "Hello" and “VIT" in a string:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hello world!";
// look for "Hello"
var patt = /Hello/;
var result = patt.test(str);
// look for “VIT"
patt2 = /VIT/;
result2 = patt2.test(str);
document.getElementById("demo").innerHTML = result + "<br>" +
result2;
}
</script>
</body>
</html>
9/21/2022 6
The search() Method
The search() method takes one argument: a regular
expression.
It returns the index of the first character of the
substring matching the regular expression.
If no match is found, the method returns -1.1
var str=“University”;
var patt=/sit/;
str.search(patt);
“University".search(/sit/); //returns 6
9/21/2022 7
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Search a string for “VIT", and display the position of
the match:</p>
<p id="demo"></p>
<script>
var str = "Visit VIT!";
var n = str.search(/vit/i);
document.getElementById("demo").innerHTML = n;
</script>
</body>
</html>
9/21/2022 8
The split() Method
The split() method takes one argument: a regular
expression. It uses the regular expression as a delimiter
to split the string into an array of strings.
“University".split(/[aeiou]/);
/*
returns an array with the following values:
“n", “v", “rs", “ty”
*/
9/21/2022 9
The replace() Method
The replace() method takes two arguments: a regular
expression and a string.
It replaces the first regular expression match with the
string.
If the g flag is used in the regular expression, it
replaces all matches with the string.
“Hello World Hello World".replace(/World/g, “VIT");
//returns
Hello VIT Hello VIT
“Hello".replace(/[aeiou]/g, "x"); //returns Hxllx
9/21/2022 10
The match() Method
The match() method takes one argument: a regular
expression.
It returns each substring that matches the regular
expression pattern.
“University".match(/[aeiou]/g);
returns an array with the following values:
“U", “i", “e", “i“
9/21/2022 11
<html>
<body>
<p>Click the button to do a global search for the
character "h" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Is this all there is?";
var patt1 = /[i]/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML =
result;
}
</script>
</body></html>
9/21/2022 12
<html><head>
<title>JavaScript Form Validation: Empty form fields </title>
<style>body{font-family:Verdana;}</style>
</head><body>
<script>
function check(myform){
if (myform.myname.value == "" || myform.myname.value == null)
{ alert("Name is mandatory");
return false; }
if(myform.myphone.value == "" || myform.myphone.value == null)
{ alert("Phone number is mandatory");
return false; }
else{ return true; } }
</script>
<form name="formvalidate" onSubmit="return check(formvalidate)">
<p> Name :
<input type="text" size="50" name="myname" /> </p>
<p> Phone No :
<input type="text" size="50" name="myphone" /> </p>
<p>
<input type="submit" value="Submit" />
<input
9/21/2022 type="reset" value="Clear" /> 13
Position matching
Defining character positions
9/21/2022 14
Literals
Symbol Description
Alphanumeric All alphabetical and numerical characters match themselves
literally. So /2 days/ will match "2 days" inside a string.
\n Matches a new line character
\f Matches a form feed character
\r Matches carriage return character
\t Matches a horizontal tab character
\v Matches a vertical tab character
\xxx Matches the ASCII character expressed by the octal number xxx.
"\50" matches left parentheses character "("
\xdd Matches the ASCII character expressed by the hex number dd.
"\x28" matches left parentheses character "("
\uxxxx Matches the ASCII character expressed by the UNICODE xxxx.
"\u00A3" matches "£“.
9/21/2022 15
Defining character positions
9/21/2022 16
<html>
<body>
<p>Click the button to do a global search for digits in a
string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Give 100%!";
var patt1 = /\d/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML =
result;
}
</script>
</body>
</html>
9/21/2022 17
<html><head><title>JavaScript form validation - checking non-
empty</title>
</head><body onload='document.form1.text1.focus()'>
<div><h2>Input an Phone No.[xxxxxxxxxx] and Submit</h2>
<form name="form1">
<input type='text' name='text1'/>
<input type="submit" name="submit" value="Submit"
onclick="phonenumber(document.form1.text1)"/>
</form></div>
<script>function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if(inputtxt.value.match(phoneno))
{
return true; }
else {
alert("Not a valid Phone Number");
return false; } }
</script>
</body>
</html>
9/21/2022 18
Defining character positions
9/21/2022 19
<html>
<body>
<p>Click the button to do a global search for the character-span [a-h] in a
string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Is tHis all there is?";
var patt1 = /[a-h]/ig;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
9/21/2022 20
<html>
<body>
<p>Click the button to do a global search for the
character-span [a-h] in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Is this all there is?";
var patt1 = /[a-h]/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML =
result;
}</script></body></html>
9/21/2022 21
<html>
<body>
<p>Click the button to do a global search for the
numbers 1 to 4 in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "123456789";
var patt1 = /[1-4]/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML =
result;
}
</script></body>
</html>
9/21/2022 22
Repeating characters
9/21/2022 23
<html>
<body>
<p>Click the button to do a global search for at least one
"o" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hellooo World! Hello W3Schools!";
var patt1 = /o+/g; output: 000 0 0 00
var result = str.match(patt1);
document.getElementById("demo").innerHTML =
result;
}
</script>
</body></html>
9/21/2022 24
<html>
<body>
<p>Click the button to do a global search for an "l",
followed by zero or more "o" characters.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hellooo World! Hello W3Schools!";
var patt1 = /lo*/g; l l000 l l l0 l
var result = str.match(patt1);
document.getElementById("demo").innerHTML =
result;
}</script>
9/21/2022 25
<html>
<body>
<p>Click the button to do a global search for a "1",
followed by zero or more "0" characters.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "1, 100 or 1000?";
var patt1 = /10*/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML =
result;
}
</script>
</body></html>
9/21/2022 26
Repeating characters
9/21/2022 27
Grouping and Alteration
Symbol Description
() Grouping characters together to create a clause. May be nested.
Example:
/(abc)+(def)/ matches one or more occurrences of "abc" followed by
one occurrence of "def".
| Alternation combines clauses into one regular expression and then
matches any of the individual clauses. Similar to "OR" statement.
Example:
/(ab)|(cd)|(ef)/ matches "ab" or "cd" or "ef".
9/21/2022 28
Pattern switches or flags
Property Description
i Ignore the case of characters.
/The/i matches "the" and "The" and "tHe"
g Global search for all occurrences of a pattern
Ex:
/ain/g matches both "ain"s in "No pain no gain", instead of just
the first.
gi Global search, ignore case.
Ex:
/it/gi matches all "it"s in "It is our IT department"
9/21/2022 29
Back references
Backreferences are special wildcards that refer back to
a subpattern within a pattern.
They can be used to make sure that two subpatterns
match.
The first subpattern in a pattern is referenced as \1, the
second is referenced as \2, and so on.
Ex: ([bmpw])o\1
matches "bob", "mom", "pop", and "wow", but not
"bop" or "pow“
^\d{3}([\- ]?)\d{2}\1\d{4}$ ---- in checkSSN program
9/21/2022 30
Backslash
The backslash (\) is also used when you wish to match
a special character literally. For example, if you wish to
match the symbol "$" literally instead of have it signal
the end of the string, backslash it: /\$/
9/21/2022 31
Escape sequences
9/21/2022 32
Some Examples in form validation
//contact no.
var reg=/^([0-9]{7,12})$/;
// following pattern specifies the rules for email
/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-
z]{2,4})$/;
// following pattern allows exactly 6 character long
string having numeric characters only
// "^" indicates begining of string, "$" indicates end of
string.
var reg = /^([0-9]{6})$/;
9/21/2022 33
References
http://www.advanced-javascript-
tutorial.com/RegularExpressions.cfm#.UgCO86wVg1h
http://www.javascriptkit.com/javatutors/re2.shtml
Web Technologies – Uttam K.Roy
9/21/2022 34