Unit 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Unit 5

JavaScript Regular Expressions


A regular expression is a sequence of characters that forms a search pattern.
The search pattern can be used for text search and text replace operations.
What Is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what you are
searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.

Syntax
/pattern/modifiers;

Example
var patt = /arrow/i;

Example explained:
/arrow/i is a regular expression
arrow is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).

Modifiers
Modifiers are used to perform case-insensitive and global searches:
Modifier Description

g Perform a global match (find all matches rather than stopping after the first match)

i Perform case-insensitive matching

m Perform multiline matching

test()
The test() method tests for a match in a string.
This method returns true if it finds a match, otherwise it returns false.

Syntax

RegExpObject.test(string)

Client Side Scripting (Unit 5) Arrow Computer Academy


Q] Write a program to check whether the string contains the given pattern or not.

<!DOCTYPE html>
<html>
</head>
<script type="text/javascript">
var p=/arrow computer academy/i
function testMatch()
{
var str = T1.value;
if(p.test(str))
{
alert("String " + str + " contains the given pattern")
}
else
{
alert("String " + str + " does not contains the given pattern")
}
}
</script>
</head>
<body>
Enter string <input type="text" id="T1">
<button onclick="testMatch()">Try it</button>
</body>
</html>

Client Side Scripting (Unit 5) Arrow Computer Academy


Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.
Sr.No. Expression & Description

1 [...]
Any one character between the brackets.
Ex: [abc]

2 [^...]
Any one character not between the brackets.
Ex: [^abc]

3 [0-9]
It matches any decimal digit from 0 through 9.

4 [^0-9]
Find any character NOT between the brackets (any non-
digit)

4 [a-z]
It matches any character from lowercase a through
lowercase z.

5 [A-Z]
It matches any character from uppercase A through
uppercase Z.

6 [a-Z]
It matches any character from lowercase a through
uppercase Z.

7 (x|y)
Find any of the alternatives specified

The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging
from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.

Client Side Scripting (Unit 5) Arrow Computer Academy


Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted
by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all
follow a character sequence.

Sr.No. Expression & Description

1 p+
It matches any string containing one or more p's.

2 p*
It matches any string containing zero or more p's.

3 p?
It matches any string containing at most one p.

4 p{N}
It matches any string containing a sequence of N p's

5 p{2,3}
It matches any string containing a sequence of two or three p's.

6 p{2, }
It matches any string containing a sequence of at least two p's.

7 p$
It matches any string with p at the end of it.

8 ^p
It matches any string with p at the beginning of it.

Client Side Scripting (Unit 5) Arrow Computer Academy


Metacharacter
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the
combination a special meaning.

Metacharacter Description

. Find a single character, except newline or line terminator

\w Find a word character


A word character is a character from a-z, A-Z, 0-9, including the _ (underscore)
character.

\W Find a non-word character

\d Find a digit

\D Find a non-digit character

\s Find a whitespace character

\S Find a non-whitespace character

\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like
this: HI\b

\B Find a match, but not at the beginning/end of a word

\0 Find a NULL character


\0 returns the position where the NUL character was found. If no match is
found, it returns -1.

\n Find a new line character


\n returns the position where the newline character was found. If no match is
found, it returns -1.

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

\v Find a vertical tab character

\xxx Find the character specified by an octal number xxx

\xdd Find the character specified by a hexadecimal number dd

\udddd Find the Unicode character specified by a hexadecimal number dddd

Client Side Scripting (Unit 5) Arrow Computer Academy


RegExp Methods

Method Description

test() Tests for a match in a string. It returns true or false.

Returns an array containing all of the matches, including capturing groups, or null if
match()
no match is found.

Tests for a match in a string. It returns the index of the match, or -1 if the search
search()
fails.

Executes a search for a match in a string, and replaces the matched substring with a
replace()
replacement substring

Uses a regular expression or a fixed string to break a string into an array of


split()
substrings.

Matching Words

The match() function is used to match a word in given string.


<!DOCTYPE html>
<html>
<body>

<p>Enter some value in textbox and click on button to find characters NOT inside the
brackets.</p>

<script>
function myFunction() {
var patt1 = /student/gi;
var str = T1.value;
var result = str.match(patt1);
if(result!=null)
{
alert(" Entered string contains word student");
}
else
{
alert(" Entered string does not contain word student");
}
}
</script>
Enter string <input type="text" id="T1">
<button onclick="myFunction()">Try it</button>

</body>
</html>

Client Side Scripting (Unit 5) Arrow Computer Academy


Finding a Non Matching characters

The [^abc] expression is used to find any character NOT between the brackets.
^ symbol is placed at first position.
Ex: [^abc] It finds any non matching character i.e. any character except a,b,c.

<!DOCTYPE html>
<html>
<body>

<p>Enter some value in textbox and click on button to find characters NOT inside the
brackets.</p>

<script>
function myFunction() {
var patt1 = /[^ht]/gi;
var str = T1.value;
var result = str.match(patt1);
alert("Non Matching characters are "+ result);
}
</script>
Enter string <input type="text" id="T1">
<button onclick="myFunction()">Try it</button>

</body>
</html>

Entering Range of Characters:


For matching any digit we need not have to enter every digit right from 0 to 9.
Similarly for matching letters we need not have to test with every single alphabet. We can achieve this by
entering range of Characters.

For example - to match a characters from ‘a’ to ‘d’ we must have a regular expression as [a-d]. Thus placing
the range within a square bracket helps us to evaluate a complete range of set of characters.

<!DOCTYPE html>
<html>
<body>

<p>Enter some value in textbox and click on button to find characters within the range.</p>

<script>
function myFunction() {
var patt1 = /[a-d]/gi;
var str = T1.value;
var result = str.match(patt1);
alert("characters within the range are "+ result);
}
</script>

Client Side Scripting (Unit 5) Arrow Computer Academy


Enter string <input type="text" id="T1">
<button onclick="myFunction()">Try it</button>

</body>
</html>

Matching Digits and Non Digits


The string may contain digits and non-digits i.e. characters other than digits.
Determining whether the string contains digits or non digits is a common task in any search
pattern. Validating telephone number is one of the task where it requires Matching Digits.
This can be simplified by JavaScript by writing the regular expression.
If we want to search digits, then we use \d and if we want to search non-digits, then we use \D

Example1 : To check whether string contains digits or not

<!DOCTYPE html>
<html>
</head>
<script type="text/javascript">
var p=/\d/i
function testMatch()
{
var str = T1.value;
if(p.test(str))
{
alert("String " + str + " contains the digits")
}
else
{
alert("String " + str + " does not contains digits")
}
}
</script>
</head>
<body>
Enter string <input type="text" id="T1">
<button onclick="testMatch()">Try it</button>
</body>
</html>

Client Side Scripting (Unit 5) Arrow Computer Academy


Example 2 : To check whether string contains digits or not

<!DOCTYPE html>
<html>
</head>
<script type="text/javascript">
var p=/\D/g
function testMatch()
{
var str = T1.value;
if(p.test(str))
{
alert("Enter only Numbers")
}
else
{
alert("Correct Number")
}
}
</script>
</head>
<body>
Enter Phone number <input type="text" id="T1">
<button onclick="testMatch()">Try it</button>
</body>
</html>

Matching Punctuations and Symbols


• The special symbol w tells the browser to determine whether the text contains a letter, number,
or an
underscore.
The W special symbol tells the browser to determine whether the text contains other than a letter,
number, or an underscore.
Using \W is equivalent to using [a-zA-Z0-9_]. The last_indicates underscore character.

Example to test whether string contains any punctuation or special symbols

<!DOCTYPE html>
<html>
</head>
<script type="text/javascript">
var p=/\W/i
function testMatch()
{
var str = T1.value;
if(p.test(str))
{
alert("String " + str + " contains the special character")
}
else
{
alert("String " + str + " does not contain special character")

Client Side Scripting (Unit 5) Arrow Computer Academy


}
}
</script>
</head>
<body>
Enter string <input type="text" id="T1">
<button onclick="testMatch()">Try it</button>
</body>
</html>

Replacing a Text using Regular Expressions


By using replace function, we can replace the pattern in given string.
The first parameter in the replace function is the string which is to be replaced and the second parameter is
the string which replaces old string.
For example- Consider following JavaScript in which the word 'country' is replaced by 'India

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
str="Welcome to Arrow";
document.write(str);
function myfunction(str)
{
new_str=str.replace("Arrow", "Arrow Computer Academy");
document.write(new_str);
}
</script>
</head>
<body>
<br>
<input type="button" value="Replace" onclick="myfunction(str)">
</body>
</html>

Client Side Scripting (Unit 5) Arrow Computer Academy


Frames
HTML frames are used to divide your browser window into multiple sections where each section
can load a separate HTML document.
A collection of frames in the browser window is known as a frameset.
The window is divided into frames in a similar way the tables are organized: into rows and
columns.
Using multiple views we can keep certain information visible and at the same time other views
are scrolled or replaced.

Creating Frames
To use frames on a page we use <frameset> tag instead of <body> tag.
The <frameset> tag defines, how to divide the window into frames. The rows attribute of
<frameset> tag defines horizontal frames and cols attribute defines vertical frames.
Each frame is indicated by <frame> tag and it defines which HTML document shall open into the
frame.
Example1:
<frameset cols= “ 150, * ” >

will allow us to divide the window into two columns (i.e. in two vertical frames).
One frame occupying the size of 150 pixels and the other occupies the remaining portion of the
window.

Example 2:
<frameset rows= " *, 120 ”>
will divide the window into two rows ( i.e. in two horizontal frames).
The second part of horizontal Frame will be of 120 pixels and upper horizontal frame will occupy
remaining portion of the window.

Similarly we can also specify the frameset in percentage form.


For Example
<frameset rows=”30%, 70%”>

Client Side Scripting (Unit 5) Arrow Computer Academy


The <frameset> Tag Attributes
Following are important attributes of the <frameset> tag –

Sr Attribute & Description

cols
Specifies how many columns are contained in the frameset and the size of each column.
You can specify the width of each column in one of the four ways −
Absolute values in pixels. For example, to create three vertical frames, use cols = "100,
500, 100".
A percentage of the browser window. For example, to create three vertical frames,
use cols = "10%, 80%, 10%".
1 Using a wildcard symbol.
For example, to create three vertical frames, use cols = "10%, *, 10%". In this case
wildcard takes remainder of the window.
As relative widths of the browser window.
For example, to create three vertical frames, use cols = "3*, 2*, 1*". This is an alternative
to percentages.
You can use relative widths of the browser window. Here the window is divided into
sixths: the first column takes up half of the window, the second takes one third, and the
third takes one sixth.

rows
This attribute works just like the cols attribute and takes the same values, but it is used
2 to specify the rows in the frameset.
For example, to create two horizontal frames, use rows = "10%, 90%".
You can specify the height of each row in the same way as explained above for columns.

border
3 This attribute specifies the width of the border of each frame in pixels.
For example, border = "5". A value of zero means no border.

frameborder
4 This attribute specifies whether a three-dimensional border should be displayed
between frames. This attribute takes value either 1 (yes) or 0 (no). For example
frameborder = "0" specifies no border.

framespacing
This attribute specifies the amount of space between frames in a frameset. This can take
5 any integer value.
For example framespacing = "10" means there should be 10 pixels spacing between
each frames.

Client Side Scripting (Unit 5) Arrow Computer Academy


The <frame> Tag Attributes
Following are the important attributes of <frame> tag –

Sr Attribute & Description

src
1 This attribute is used to give the file name that should be loaded in the frame. Its
value can be any URL. For example, src = "/html/top_frame.htm" will load an HTML
file available in html directory.

name
This attribute allows you to give a name to a frame. It is used to indicate which
2 frame a document should be loaded into. This is especially important when you
want to create links in one frame that load pages into an another frame, in which
case the second frame needs a name to identify itself as the target of the link.

frameborder
3 This attribute specifies whether or not the borders of that frame are shown; it
overrides the value given in the frameborder attribute on the <frameset> tag if one
is given, and this can take values either 1 (yes) or 0 (no).

marginwidth
4 This attribute allows you to specify the width of the space between the left and
right of the frame's borders and the frame's content. The value is given in pixels.
For example marginwidth = "10".

marginheight
5 This attribute allows you to specify the height of the space between the top and
bottom of the frame's borders and its contents. The value is given in pixels. For
example marginheight = "10".

noresize
6 By default, you can resize any frame by clicking and dragging on the borders of a
frame. The noresize attribute prevents a user from being able to resize the frame.
For example noresize = "noresize".

scrolling
7 This attribute controls the appearance of the scrollbars that appear on the frame.
This takes values either "yes", "no" or "auto". For example scrolling = "no" means it
should not have scroll bars.

Client Side Scripting (Unit 5) Arrow Computer Academy


Example 1:

<!DOCTYPE html>
<html>

<head>
<title>HTML Frames</title>
</head>

<frameset cols = "25%,50%,25%">


<frame name = "left" src = "pr4.html" />
<frame name = "center" src = "pr4.html" />
<frame name = "right" src = "pr4.html" />

<noframes>
<body>Your browser does not support frames.</body>
</noframes>
</frameset>

</html>

Example 2:

</html>

<!DOCTYPE html>
<html>

<head>
<title>HTML Target Frames</title>
</head>

<frameset cols = "200, *">


<frame name = "left" src = "pr4.html" />
<frame name = "center" src = "pr4.html" />

<noframes>
<body>Your browser does not support frames.</body>
</noframes>
</frameset>

</html>

Client Side Scripting (Unit 5) Arrow Computer Academy


Rollover
Rollover means change in the appearance of the object, when user moves his or her mouse over an
object on the page
The rollover effect is mainly used in web page designing for advertising purpose.

Creating Rollover
On many web pages, JavaScript rollovers are handled by adding an onmouseover and onmouseout
event on images.

(1) onmouseover is triggered when the mouse moves over an element


(2) onmouseout is triggered when the mouse moves away from the element

Image Rollover
<html>
<head>
<title>Creating Rollover</title>
</head>
<body>
<img src="mickey1.jpeg" boarder="0px" width="650px" height="550px" onmouseover="src=
'mickey.jpeg'" onmouseout="src= 'mickey1.jpeg'">
</body>
</html>

Text Rollover
Text rollover is a technique in which whenever user rollover the text, JavaScript allows to change the page
element usually some graphics image.
Carefully placed rollovers can enhance a visitors experience when browsing the web page.
<html>
<body>
<a>
<img src ="mango.jpeg" name="fruit" width="650px" height="550px">
</a>
<a onmouseover="document.fruit.src='mango.jpeg'">
<br>
<b><u>Mango</u></b>
</a>
<br><br><br>

<a onmouseover="document.fruit.src='banana.jpeg'">
<b><u>banana</u></b>
</a>
<br><br><br>
<a onmouseover="document.fruit.src='pineapple.jpeg'">
<b><u>pineapple</u></b>
</a>
<br><br/><br/>
</body>
</html>

Client Side Scripting (Unit 5) Arrow Computer Academy


Multiple Actions for Rollover
<html>
<head>

<script type="text/javascript">
function display1()

{
document.fruit.src='mango.jpeg'
document.getElementById('para').innerHTML="Trees of mango are larger than
Pineapple"
}

function display2()

{
document.fruit.src='pineapple.jpeg'
document.getElementById('para').innerHTML="Trees of pineapple are smaller than
mango"
}

</script>
</head>
<body>

<a onmouseover="display1()">
<br>
<b><u>mango</u></b>
</a>
<br>
<a onmouseover="display2()">
<br>
<b><u>Pineapple</u></b>
</a>
<br><br><br>
<a>
<img src ="mango.jpeg" name="fruit" width="650px" height="550px">
</a>
<p id="para">Trees of mango are larger than Pineapple </p>

</body>
</html>

Client Side Scripting (Unit 5) Arrow Computer Academy

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy