0% found this document useful (0 votes)
23 views16 pages

Chapter 5 Regular Expressions, Rollover and Frames Regular Expression

Uploaded by

sharvari dhokte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views16 pages

Chapter 5 Regular Expressions, Rollover and Frames Regular Expression

Uploaded by

sharvari dhokte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 5 Regular Expressions, Rollover and frames

Regular Expression

• A regular expression is very similar to a mathematical expression, except a regular


expression tells the browser how to manipulate text rather than numbers by using
special symbols as operators.

• 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
operation

Syntax:

• A regular expression could be defined with the RegExp () constructor, as follows −

var pattern = new RegExp(pattern, attributes);

or simply

var pattern = /pattern/attributes;

Where

• pattern − A string that specifies the pattern of the regular expression or another
regular expression.

• attributes − An optional string containing any of the "g", "i", and "m" attributes that
specify global, case-insensitive, and multi-line matches, respectively.

Ex:

• var patt = /kkwp/i;

/kkwp/i is a regular expression.

• kkwp is a pattern (to be used in a search).

• i is a attribute (modifies the search to be case-insensitive).

Language of Regular Expression:

• By learning the language of a regular expression one make a browser understands it


by manipulating any text entered into a form on your web page.

• The words of the regular expression language are called special characters and act
similarly to an operator in a mathematical expression.

• Special characters tell the browser to perform an operation on text.


• You can place any number of characters, numbers, or punctuation or symbols within
the brackets, and the browser will determine whether they exist in the text

• If you want to search for a symbol that is also a special character, you must precede
the symbol with a backslash (\), which is known as an escape character.

• The backslash tells the browser to ignore the special meaning of the symbol.

Here's what you'd need to write to search for the ‘[‘ symbol in text.

• Ex: / [ \ [ ] /

• Here's how the browser reads this regular expression:

1. The ‘/’ character tells the browser that this is the beginning of a regular expression.

2. The ‘[‘ character tells the browser to search the text for the following character(s).

3. The ‘\’ tells the browser to ignore the special meaning of the next character.

4. The ‘[‘ character is the character that the browser will search for in the text.

5. The ‘]’ character tells the browser that there are no more characters to search for.

6. The ‘/’ character tells the browser that this is the end of the regular expression.

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.


Example:

Sr. Expression Description


No.
1. [^a-zA-Z] It matches any string not containing any of the
characters ranging from a through z and A through Z.
2. p.p It matches any string containing p, followed by any
character, in turn followed by another p.
3. ^.{2}$ It matches any string containing exactly two characters.
4. <b>(.*)</b> It matches any string enclosed within <b> and </b>.
5. p(hp)* It matches any string containing a p followed by zero or
more instances of the sequence hp.

Literal Characters:

Sr. Character Description


No.
1. Alphanumeric Itself

2. \0 The NUL character (\u0000)

3. \t Tab (\u0009)

4. \n Newline (\u000A)

5. \v Vertical tab (\u000B)

6. \f Form feed (\u000C)

7. \r Carriage return (\u000D)

8. \xnn The Latin character specified by the hexadecimal number nn; for
example, \x0A is the same as \n
9. \uxxxx The Unicode character specified by the hexadecimal number xxxx;
for example, \u0009 is the same as \t
10. \cX The control character ^X; for example, \cJ is equivalent to the
newline character \n
Meta characters:

• A metacharacter is simply an alphabetical character preceded by a backslash that acts


to give the combination a special meaning.

• For instance, you can search for a large sum of money using the '\d' metacharacter:
/([\d]+)000/, Here \d will search for any string of numerical character.

The following table lists a set of metacharacters which can be used in PERL Style
Regular Expressions

Explanation:

Sr. Character Description


No.
1. . a single character

2. \s a whitespace character (space, tab, newline)

3. \S non-whitespace character

4. \d a digit (0-9)

5. \D a non-digit

6. \w a word character (a-z, A-Z, 0-9, _)

7. \W a non-word character

8. [\b] a literal backspace (special case).

9. [aeiou] matches a single character in the given set

10. [^aeiou] matches a single character outside the given set

11. (foo|bar|baz) matches any of the alternatives specified

Finding Nonmatching Characters:

• Sometimes a JavaScript application prohibits certain characters from appearing within


text entered into a form, such as a hyphen (-).

• You can direct the browser to search for illegal character(s) by specifying the illegal
character(s) within brackets and by placing the caret (^) as the first character in the
bracket.

• Let's see how this works in the following example:

/[ ^ \- ]/
• In this case, the browser is asked to determine whether the text does not contain the
hyphen.

• The caret asks the browser to determine whether the following character(s) do not
appear in the text.

Entering a Range of Characters:

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

Sr. Expression Description


No.
1. [...] Any one character between the brackets.

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

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

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.

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

Matching Digits and Nondigits:

• Limiting an entry either to digits or nondigits is a common task for many JavaScript
applications.

• For example, a telephone number entered by a user should be a series of digits, and a
first name should be nondigits.

• You can have the browser check to see whether the text has digits or nondigits by
writing a regular expression.

• The regular expression must contain either \d or \D, depending on whether you want
the browser to search the text for digits (\d) or nondigits (\D).

• / \d / :This symbol, tells the browser to determine whether the text contains digits.
The browser returns a true if at least one digit appears in the text.

• / \D /: This symbol is used to tell the browser to search for any nondigit in the text.
This is illustrated next. The browser returns a true if a nondigit is found.
Matching Punctuation and Symbols:

• The browser determines whether text contains or doesn't contain letters, punctuation,
or symbols, such as the @ sign in an e-mail address

• By using the \w and \W we can search special symbols in a regular expression.

• The \w special symbol tells the browser to determine whether the text contains a
letter, number, or an underscore.

• The \W special symbol reverses this request by telling the browser to determine
whether the text contains a character other than a letter, number, or underscore.

• Ex: You can use the following regular expression to determine whether the product
name that was entered into the form on your web page contains a symbol:

• / \W /: Using \W is equivalent to using [a-zA-Z0-9_].

Matching Words:

• You might want the browser to search for a particular word within the text.

• A word is defined by a word boundary that is, the space between two words.

• You define a word boundary within a regular expression by using the \b special
symbol.

• The \b special symbol as a space between two words. You need to use two \b special
symbols in a regular expression.

• If you want the browser to search for a word: the first \b represents the space at the
beginning of the word and the second represents the space at the end of the word.

• Ex: /\b Bob \b/:

• You want to determine whether the name Bob appears in the text.

• Since you don't want the browser to match just text that contains the series of letters
B-o-b, such as Bobby, you'll need to use the word boundary to define Bob as a word
and not simply a series of letters.

The test() method:

• The regular expression can be test by using test() method.

• Ex:

<script>

function RegExpression() {

var name='Bob'

re = /[bt]/
if (re.test(name))

{ alert('Found') }

else

{ alert('Not Found') }

</script>

Output:

• A true is returned if either b or t or both are found in the name Bob; otherwise a false
is returned.

• Depending on this result, the appropriate alert dialog box is displayed on the screen.

Replace Text Using a Regular Expression:

• The replace() method is used to replace portion of text.

• It returns a modified string where the pattern is replaced.

• Ex: /\b Bob \b/g

re = / \b Bob \b /

text = 'Hello, Bob and welcome to our web site.'

text = text.replace(re, 'Mary')

Placing ‘g’ at the end of the regular expression, which tells the browser to replace all
occurrences of the regular expression in the string.

Steps:

1. Create a regular expression that identifies portion of text that you want replaced.

2. Determine the replacement text. Pass both of these to the replace() method, and
browser follows the direction given in the regular expression to locate the text.

3. If the text is found, the browser replaces it with the new text that you provided.

4. The next example tells the browser to replace Bob with Mary in the text.

5. The regular expression specifies the word Bob.

6. The replace() method of the string object is then called to use the regular expression
to search for Bob within the text and then replace Bob with Mary.

7. However, the original string isn't modified. The modified string is returned by the
replace() method.
Replacing Like Values:

• A regular expression can be written to search for variations of a name and replace it
with a standardized name.

• To do this, the regular expression must contain literal characters and wildcard
characters.

• A literal character is a letter, number, or symbol that must match exactly within the
text.

• A wildcard is a special symbol that tells the browser to accept one or multiple
unspecified characters as a match.

• Two types of wildcards can be used: a period (.) and an asterisk (*).

• The period tells the browser to match any single character, while the asterisk indicates
zero or more occurrences of whatever precedes it.

• Ex: The following matches Bob but not Bobby, because a single wildcard character is
used:

• / Bob. /

• However, this regular expression matches both Bob and Bobby because the multiple
character wildcard is used:

• / Bob.* /

Return the Matched Characters:

• Sometimes you need to retrieve characters that match a regular expression rather than
simply testing whether those characters exist in the text or not.

• You can have the browser return characters that match the pattern in your regular
expression by calling the exec() method of the regular expression object.

The exec() method returns an array. The first array element contains the text that matches
your regular expression

• Ex: The following regular expression matches Bob and any word that begins with B-
o-b.

/ \b Bob.* \b /

We'll need to do the following:

1. Create the regular expression object and assign it the regular expression: re = / \b
Bob.* \b /
2. Call the exec() method, passing it the text and assigning the return value to an array
variable. re = / \b Bob.* \b /

MyArray = re.exec('Hello, my name is Bobby.')

3. We then display the value of the first array element:

re = / \b Bob.* \b /

MyArray = re.exec('Hello, my name is Bobby.')

alert('Welcome, ' + MyArray[0]).

Symbols to remember for Regular Expression:

Regular Expression Properties

Sr. No. Reg. Exp. Object Properties

1. $1 (through $9) Parenthesized substring matches

2. $_ Same as input

3. $* Same as multiline

4. $& Same as last Match

5. $+ Same as last Parenthesis


6. $` Same as left Context

7. $' Same as right Context

8. constructor Specifies the function that creates an object's prototype

9. global Search globally (g modifier in use)

10. ignoreCase Search case-insensitive (i modifier in use)

11. input The string to search if no string is passed

12. lastIndex The index at which to start the next match

13. lastMatch The last match characters

14. lastParen The last parenthesized substring match

15. leftContext The substring to the left of the most recent match

16. multiline Whether strings are searched across multiple lines

17. prototype Allows the addition of properties to all objects

18. rightContext The substring to the right of the most recent match

19. source The regular expression pattern itself

Regular Expression Properties

1. constructor: It returns a reference to the array function that created the instance's
prototype.

Syntax

RegExp.constructor

Return Value

Returns the function that created this object's instance.

Example:

<html>

<head>
<title>JavaScript RegExp constructor Property</title>

</head>

<body>

<script type = "text/javascript">

var re = new RegExp( "string" );

document.write("re.constructor is:" + re.constructor);

</script>

</body>

</html>

2. global: global is a read-only boolean property of

RegExp objects. It specifies whether a particular regular expression performs global


matching, i.e., whether it was created with the "g" attribute.

Syntax

RegExpObject.global

Return Value

Returns "TRUE" if the "g" modifier is set, "FALSE" otherwise.

Example:

<html>

<head></head>

<body>

<script type = "text/javascript">

var re = new RegExp( "string" );

if ( re.global ) document.write("Test1 - Global property is set");

else document.write("Test1 - Global property is not set");

re = new RegExp( "string", "g" );

if ( re.global ) document.write("<br />Test2 - Global property is set");

else document.write("<br />Test2 - Global property is not set");

</script>

</body>
</html>

3. ignoreCase: ignoreCase is a read-only boolean property of RegExp objects. It


specifies whether a particular regular expression performs case- insensitive
matching, i.e., whether it was created with the "i" attribute.

Syntax

RegExpObject.ignoreCase

Return Value

Returns "TRUE" if the "i" modifier is set, "FALSE" otherwise.

Example:

<html>

<head></head>

<body>

<script type = "text/javascript">

var re = new RegExp( "string" );

if ( re.global ) document.write("Test1 - Global property is set");

else document.write("Test1 - Global property is not set");

re = new RegExp( "string", "g" );

if ( re.global ) document.write("<br />Test2 - Global property is set");

else document.write("<br />Test2 - Global property is not set");

</script>

</body>

</html>

4. lastIndex: It is a read/write property of RegExp objects.


For regular expressions with the "g" attribute set, it contains an integer that specifies
the character position immediately following the last match found by the
RegExp.exec() and RegExp.test() methods.
This property allows you to call those methods repeatedly, to loop through all matches
in a string and works only if the "g" modifier is set.
exec() and test() automatically reset the lastIndex to 0 when they fail to find a match
(or another match).
Syntax: RegExpObject.lastIndex
Return Value
Returns an integer that specifies the character position immediately following the last
match.
Example:
<html>
<head></head>
<body>
<script type = "text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );

re.test(str);
document.write("Test 1 - Current Index: " + re.lastIndex);
re.test(str);
document.write("<br />Test 2 - Current Index: " + re.lastIndex);
</script>
</body>
</html>

Frames:
• Many times a web page is distributed in number of sections.
• Although this looked as though it were all contained on a single web page, actually
multiple web pages appeared on the screen at the same time, and each was displayed
in a frame.
• Frames are created using HTML, but you can interact and manipulate frames using a
JavaScript.
• All frames contain at least three web pages.
• The first frame surrounds the other frames, and this entire collection is called the
frameset.
• The other frames are within the frameset, and each is referred to as a child.

The <frameset> HTML tag:


• The frameset can be divided into columns and rows, depending on the needs of your
application.
• Columns divide the frameset vertically using the cols attribute of the <frameset> tag.
• Rows divide the frameset horizontally using the rows attribute of the <frameset> tag.

<frameset>:
• The number of rows or columns that appear in a frameset is determined by the value
assigned to these attributes.
• Each column or row is represented by a percentage that indicates the percent of the
frameset that is taken up by the column or row.
• You can also specify a width and height—it doesn't have to be a percentage of the
available window.
• Ex: <frameset rows="50%,50%">
• It divides the frame horizontally into two child windows evenly.

<frame> tag:
• After you define the frameset, you can insert a web page into each child window.
• This can be done by using the <frame> HTML tag.
• Each child window has its own <frame> tag.
• You specify the web page that will be displayed in the child window by defining a
value for the src attribute of the <frame> tag.
• A unique name can also be specified for the child window by assigning the name to
the name attribute of the <frame> tag
• Ex: <frame src="WebPage1.html" name="topPage" />
• You'll need to define a <frame> tag within the <frameset> tag for each child window
contained in the <frameset> tag.
• The first <frame> tag within the <frameset> tag refers to the upper left–most child
window.
• Subsequent <frame> tags refers to child windows that appear left to right, top to
bottom within the <frameset> tag.
• Ex:
• <!—Dividing a Screen using <franeset>
• <html>
• <head> </head>
• <frameset rows="50% , 50%">
• <frame src="WebPage1.html" name="topPage" />
• <frame src="WebPage2.html" name="bottomPage" />
• </frameset>
• </html>

Invisible Borders:
• It is possible to use frames by hiding the borders around the child windows within
your frameset.
• The border can be hidden by setting the frameborder and border attributes of the
<frame> tag to zero (0).
Ex:
<html>
<head></head>
<frameset rows="50%,50%">
<frame src="WebPage1.html" name="topPage"
frameborder="0" border="0" />
<frame src="WebPage2.html" name="bottomPage"
frameborder="0" border="0" />
</frameset> </html>

Changing the Focus of a Child Window:


• The last child window that is created has the focus by default; however, you can give
any child window the focus by changing the focus after all the web pages have loaded
in their corresponding child windows.
• You do this by calling the focus() method of the child window.
• You can call the focus() method from a JavaScript function or directly in response to
an event such as the onclick event.
• The reference to parent bottomPage is needed to get past the security issues.
• parent.bottomPage.focus();
Writing to a Child Window:
• The content of a child window is a web page that exists on the web server.
• However, you can dynamically create the content when you define the frameset by
directly writing to the child window from a JavaScript

Accessing Elements of Another Child Window:


• You can access and change the value of elements of another child window by directly
referencing the element from within your JavaScript.
• You must explicitly specify the full path to the element in the JavaScript statement
that references the element, and it must be from the same domain as the web page;
otherwise, a security violation occurs.
• parent.topPage.Form1.WebPage1.value='New Label'

Rollover:
• Rollovers are used to make a web page alive, by altering its appearance as the visitor
scans the contents of the web page with the mouse.
• Any object on a web page can be changed with a rollover.
• Rollovers are commonly used on product pages to display details about merchandise
for sale online.

Creating Rollover:
• A rollover is caused by an event called onmouseover and occurs when a visitor to
your web site moves the mouse over an object that appears on the page.
• An object can be an image, text, or any element of a form.
Ex: <IMG height="92" src="7441805.gif" width="70"
border="0" onmouseover="src='0072253630.jpeg'">
• Here, the original image is the 7441805.gif file. The new image is the
0072253630.jpeg file.
• The onmouseover attribute is assigned the complete assignment statement
(src='0072253630.jpeg'), which tells the browser to replace the 7441805.gif image
with 0072253630.jpeg.

Creating Rollback:
• you'll want to roll back, or reverse changes, of the onmouseover event when the
visitor moves the cursor away from the object.
• For example, you may want the original image to return to the screen after the mouse
is moved away, replacing the image that was displayed when the onmouseover event
occurred.
• You can do this by reacting to the onmouseout event, which occurs whenever the
mouse cursor is moved off an object.

More Efficient Rollovers:


• An efficient way of handling rollovers is to load images into an array when your web
page loads.
• The browser loads each image once the first time the image is referenced in the web
page.
• Typically, the default setting for the browser is to check the browser cache for
subsequent references for the image rather than download the image again from the
web server.
• Any delay in transmission is likely to be noticed by the visitor
• You can reduce this delay by creating a JavaScript that loads all the images into
memory once at the beginning of the JavaScript, where they can be quickly called
upon as the onmouseover event occurs

You might also like