Title: JavaScript II: Into the Details
1JavaScript II Into the Details
- Marek Podgorny, EECS, Syracuse University, and
CollabWorx
2JavaScript Syntax
3Basic Syntax
- JavaScript syntax resembles Java and C
- Braces are used for grouping
- Use single or double quotes (equivalently) around
string literals - Escapes \b \t \n \f \r \" \' \\
- Other literals null, true, and false
- JavaScript is case-sensitive while HTML is not
(which sometimes leads to problems!)
4Variables
- Variables (identifiers) must begin with a letter,
underscore, or dollar sign - var a-zA-Z_a-zA-Z0-9_
- Declare variables in var statementsvar aNumber
137var aString "1" - JavaScript entities in HTML attributesltIMG
SRC"v1" WIDTH"v2"gtwhere v1 and v2 are
JavaScript variables
5Operators
- Assignment operators - / ltlt gtgt
gtgtgt - JavaScript supports the usual arithmetic
operators, as well as -- - Concatenation operator
- Bit operators ltlt gtgt gtgtgt
- Relational operators gt gt lt lt !
- Logical operators !
6Expressions
- Examples
- sum x // sum sum x
- r - n q
- s "temp" 1 // assign "temp1" to s
- phi (1 Math.sqrt(5))/2
- valid (age gt 21 age lt 65)
- An if-expression returns a value
- p ( k lt 0 ) ? 1/y y
7Reserved Words
8Statements
- JavaScript statements include break, continue,
do, for, function, if, return, switch, var,
while, and with - Multiple statements on one line are separated by
semicolons - Statement blocks are delimited by braces
- Comments come in two flavors/ any text
including newlines /// comment terminated by
newline
9The if Statement
- Assuming Boolean variable isWhite
- if ( isWhite )
- document.bgColor "pink"
- isWhite false
- else
- document.bgColor "white"
- isWhite true
-
- The else block is optional, of course
10The switch Statement
- The switch statement is new is JS 1.2switch (
fruit ) case "oranges" price 0.59
break case "apples" price 0.32 break
case "bananas" price 0.48 break
default price null
11The for Statement
- A simple for-loop
- // Compute xk for k gt 0
- for (var y1, i0 iltk i)
- y x
-
- Here is another type of for-loop
- for (var prop in object)
- statements
-
12The while Statement
- A more general looping structure
- // Compute r m n for m,n gt 0
- var r m
- while ( r gt n )
- r - n
-
- break, labeled break, and continue are permitted
in for and while loops - JavaScript supports recursion as well
13The dowhile Statement
- A dowhile loop tests its condition at the bottom
of the loop do statements while (
condition ) - In this case, the statements in the loop body are
guaranteed to execute at least once
14The with Statement
- with ( someObject ) statements
- someObject is the default object used for any
unqualified object references is statement
scopewith ( Math ) area PIrr // Math
property PI x rcos(theta) // Math method
cos y rsin(theta) // Math method sin
15Browser Objects
16Window and Frame Objects
- A Window objectthe top-level JavaScript
objectis the reflection of a ltBODYgt or
ltFRAMESETgt tag - A browser window may be divided into sub-windows
called frames - A Frame objectthe reflection of a ltFRAMEgt
taginherits all of its properties and methods
from the Window object
17Window Properties
- window and self are synonyms for the current
window - top refers to the highest-level window in a
hierarchy of frames - parent refers to the previous window or frame in
a hierarchy of frames - A window may have a name myWin
window.open(URL)
18Window Properties (contd)
- An analogy with the UNIX shell
19Frame Properties
- A Frame object also has properties called window,
self, and parent - The most important property of the Frame object
is the frames array - Each ltFRAMEgt tag automatically creates an entry
in the frames array - Frames may also have names, as inltFRAME
NAME"upperFrame"gt
20Frame Example
- lt!-- File index.html --gt
- ltHTMLgt
- ltFRAMESET ROWS"90,10"gt
- ltFRAME SRC"skeleton.html"
- NAME"upperFrame"gt
- ltFRAME SRC"navigate.html"
- NAME"navigateFrame"gt
- lt/FRAMESETgt
- ltNOFRAMESgt...lt/NOFRAMESgt
- lt/HTMLgt
21Frame Example (contd)
- lt!-- File skeleton.html --gtltHTMLgtltFRAMESET
ROWS"30,70"gt ltFRAME SRC"category.html
NAME"listFrame"gt ltFRAME SRC"titles.html
NAME"contentFrame"gtlt/FRAMESETgtlt/HTMLgt
22Frame Example (contd)
- Absolute references
- top.navigateFrame
- top.upperFrame
- top.upperFrame.contentFrame
- top.upperFrame.listFrame
- Relative references
- parent.upperFrame
- parent.contentFrame
- parent.parent.navigateFrame
In which documents are these references valid?
23Frameset Documents
- The ltFRAMESETgt and ltBODYgt tags are mutually
exclusive - No closing tag for ltFRAMEgt is needed
- A frameset document may contain a ltSCRIPTgt in
its ltHEADgt - Use ltNOFRAMESgt inside ltFRAMESETgt for
frames-impaired browsers
24Window and Frame Methods
- Both Window and Frame objects have blur, focus,
clearTimeout, and setTimeout methods - The Window object also has alert, close, confirm,
open, and promptmethods. For example, var msg
"The alert() method\n" msg " is handy for
debugging." window.alert( msg )
25Location Object
- The Location object corresponds to the URL of the
current document - To load a new document into the current window,
use window.location.href "foo.html"or
simply window.location "foo.html" - Location object properties href, protocol,
host, pathname, search
26Document Object
- There is one Document object (called document)
per window or frame - The Document object has numerous sub-objects
- Anchor, Applet, Embed, Area, Form, Image, Link,
Layer - and property arrays
- anchors, applets, embeds, forms,
images, links, layers
27Document Properties
- A Document object has the following color
properties alinkColor, linkColor, vlinkColor,
bgColor, and fgColor - Other Document properties include lastModified
and URL with ( document )
writeln('ltTTgt', URL, 'lt/TTgtltBRgt')
writeln('Updated ', lastModified)
28Document Properties (contd)
- To list the properties of document for ( var
prop in document ) with ( document )
write( prop " " ) writeln(
eval(prop), "ltBRgt") - Recall that the with statement qualifies all
object references within its scope
29Document Methods
- The write() and writeln() methods take a
comma-separated list of string expressions - The open() and close() methods (not to be
confused with window.open() and window.close())
open and close a document for writing, but these
are seldom used explicitly
30Form Objects
- Every Form object is the reflection of an HTML
ltFORMgt tag - The forms array may be indexed by integer or
name (i.e., forms0 or forms'myForm' ) - A Form object has many subobjects, each
corresponding to an HTML form element. These are
reflected in the elements array
31Form Properties
- Form elements are reflected in the elements
array. For example, document.forms0.elements
1is the second element of the first form - Most Form properties (action, encoding, method,
and target) are read/write variables, that is,
these properties may be modified on-the-fly
32Form Methods
- Invoking the submit() or reset() method on a Form
object has the same effect as pressing the
corresponding button - The event handlers onSubmit and onReset may be
used to override the default submit and reset
actions.
33Image Objects
- Images may be pre-loaded (they should be cached
in the ltHEADgt, especially if they are to be used
in the ltBODYgt) var images new Array( num )
for ( var i 0 i lt num i ) imagesi
new Image() imagesi.src "image" i
".gif" - This code loads files image1.gif, image2.gif,
and so on
34Image Animation
- Now suppose we have the tag ltIMG NAMEimggtin
the ltBODYgt. The following recursive method
animates the cached images var n 0
function animate() document.img.src
imagesn.src n (n 1) images.length
id setTimeout("animate()", 250)
35Layer Objects
- Think of a Layer object (new in JS 1.2) as a
dynamic document within a document - Each ltLAYERgt tag generates a Layer object and a
corresponding element in the layers array - Layers have many methods and properties (most of
which may be modified on-the-fly) - Note Layers are not supported in MSIE
36Built-in Arrays
- JavaScript has numerous built-in arrays, each
with its own length property
Plus the history arraythe only one whose name
does not end in s!
37HTML-reflected Arrays
Plus the elements array, whose parent is the Form
object
38Client-side String Methods
- Client-side JavaScript defines more than a dozen
String methods, including
39Navigator Objects
- The Navigator object contains information about
the browser - Two properties are appName and appVersion
- Methods include javaEnabled and taintEnabled
- All windows share the same Navigator object,
which is truly global
40MimeType Objects
- The MimeType object is a subobject of the
Navigator object - The mimeTypes array contains an entry for each
MIME type supported by the browser - Properties of MimeType include description, type,
and suffixes - The property enabledPlugin refers to a Plugin
object
41Plugin Objects
- Like MimeType, the Plugin object is a subobject
of the Navigator object - The plugins array contains an entry for each
installed plugin - Each Plugin object is an array of MimeType
objects. For example, navigator.plugins00.typ
eis a MIME type supported by plugins0
42More examples of constructors
43User-defined Objects
- Objects are defined with the function statement.
The following Circle object, for example, has
property r function Circle( r ) this.r
( r gt 0 ) ? r 0 - The this keyword permits this function to be used
as a constructor var c new Circle( 2.0 )
var area Math.PI c.r c.r
44User-defined Methods
- Methods are defined as Function objects
function Circle( r ) this.r ( r gt 0 ) ? r
0 this.getRadius new Function(
"return this.r" ) this.setRadius new
Function( "r", "this.r r" ) - Note The last argument of the Function
constructor is implicitly the method body
45Another Example
- Heres another examplefunction Car( make, model
) this.make make "" this.model
model "" this.color null this.setColor
new Function( "color", "this.color color"
) - Instantiate a Car object with newmyCar new
Car( "Ford", "Explorer" )myCar.setColor( "red"
)
46The prototype Property
- Methods may be added after the fact function
Circle_area() return Math.PI this.r
this.r Circle.prototype.area
Circle_area - Use the previous method as follows var radius
1/Math.sqrt( Math.PI ) var c new Circle(
radius ) var area c.area()
47The prototype Property (contd)
- We can add methods to built-in objects, too//
Does an array contain element x ?function
contains( x ) for (var i0 iltthis.length
i) if (thisi x) return true
return false - Now add the method to the Array object with the
prototype property Array.prototype.contains
contains
48Prototype-based Inheritance
- Define the parent object function Ellipse( r1,
r2 ) this.r1 ( r1 gt 0 ) ? r1 0
this.r2 ( r2 gt 0 ) ? r2 0 this.area new
Function( "return Math.PI this.r1
this.r2" ) - Define the child object function Circle( r )
this.r ( r gt 0 ) ? r 0 this.parent
Ellipse this.parent( r, r )
Circle.prototype new Ellipse
49Back to Objects
50The Global Object
- The implicitly defined Global object is the
top-level JavaScript object - It has two properties NaN (Not-a-Number) and
Infinity (but NN supports neither) - There are seven global functions
51The eval Function
- The function eval( string ) invokes the
JavaScript interpreter on its string argument,
which is evaluated in the context of the current
window (i.e., globally) - To evaluate the string in context of a particular
object, we use with - with (object) eval( string )
52Parsing Functions
- parseInt() and parseFloat() convert their
arguments to numbers parseFloat("12.34")
//returns 12.34 parseInt("12.34") //returns
12 parseFloat("12.34 ft")
//returns 12.34 parseInt("111", 2)
//returns 7 parseFloat("12.34") //returns NaN - A handy trick var numeric_var string_val - 0
53Other Global Functions
- isNaN( number ) returns true if and only if its
argument is NaN - isFinite( number ) returns false if its argument
is NaN, Infinity, or ?Infinity otherwise, it
returns true - escape( string ) returns a URL-encoded string
unescape( string ) performs the inverse operation
54Built-in Objects
- JavaScript has ten built-in objects
- plus the Global object discussed earlier
- An instance object is created with new
- var today new Date()
- var answers new Array(0,1,0)
- We will learn how to create objects in other ways
later on e.g. fred creates a null object. - plus the Global object discussed earlier
- An instance object is created with new
- var today new Date()
- var answers new Array(0,1,0)
55Array Objects
- In NN 3.0 (and even in 2.0!), we writevar
states new Array(50)states0
"Alabama"states1 "Alaska" // etc. - Every array has a length propertyvar n
states.length // n 2 - Two-dimensional arrays are allowedvar acodes
new Array(50)acodes0 new Array(205,334)
56Array Methods
- JavaScript 1.1 (and above) supports some powerful
array methods - myArray.sort( compFunc )sorts myArray according
to compFunc (a user-defined, numeric-valued
function of two arguments) function compFunc(
a, b ) return a - b - myArray.join( sep )returns a string of elements
separated by sep - myArray.reverse()reverses the order of the
elements in myArray
57Boolean Objects
- To create a false Boolean object, usenew
Boolean()new Boolean( 0 )new Boolean( null
)new Boolean( "" )new Boolean( false ) or
simply use the literal false - All other values create a Boolean object with
initial value true!
58Date Objects
- The Date constructor has many forms today
new Date() xmas new Date( 97, 12, 25 )
birthday new Date( "April 6, 1952" ) - The Date() constructor may also be used as a
function with no arguments - Time measured in milliseconds past January 1,
1970 UTC (Universal Coordinated Time) - Warning The Date object is buggy in NN2!
59Date Methods
- The Date object has no properties access to date
and time fields is via dozens of set and get
methods xmas.setYear(xmas.getYear()1) - There are two static Date methods
- Date.parse( date_string )
- Date.UTC( year, month, day )
- Both convert their argument(s) to milliseconds
past January 1, 1970 UTC
60Function Objects
- Every function statement gives rise to a Function
object - Function objects are also created with the new
operator window.onload new Function(
"document.bgColor'white'" ) - Function objects may be anonymous
- NB Function arguments are passed by value
61Function Arguments
- Functions may take an arbitrary number of
argumentsfunction User() this.name
User.arguments0 this.group
User.arguments1 this.email new Array()
var n User.arguments.length for (var i 2
i lt n i) this.emaili-2User.argumentsi
- Note the arguments array is built in
62The Math Object
- Math is the only built-in object that does not
have a constructor - Its sole purpose is to provide constants
(properties) and functions (methods) - The with statement is particularly useful in
conjunction with Math with ( Math ) x
rcos( PI/2 ) y rsin( PI/2 )
63Math Properties
- These properties are primarily for convenience
64Math Methods
Each method in the middle column requires two
arguments
65Number Objects
- There is a Number constructor, but it is rarely
used since JavaScript automatically converts
numeric literals to numeric objects as needed - Some useful properties are provided MAX_VALUE,
MIN_VALUE, NaN, NEGATIVE_INFINITY, and
POSITIVE_INFINITY
66Number Properties
- Number.MIN_VALUE is the smallest positive number
representable - Number.POSITIVE_INFINITY is returned by any
operation that is greater than Number.MAX_VALUE - Number.NEGATIVE_INFINITY is returned by any
operation that is less than ?Number.MAX_VALUE
67Number Properties (contd)
- Number.NaN is returned by parseInt() and
parseFloat() when the parsing operation fails - An attempt to divide by zero also returns
Number.NaN - Test for Number.NaN using the global boolean
function isNaN() - Note NN2.0 and MSIE3.0 do not support
Number.NaN!
68Object Objects
- The Object constructor converts its argument (any
numeric, Boolean, or string literal) to a
JavaScript object var s new Object( "EECS"
)is equivalent to var s new String( "EECS"
)This is usually unnecessary, however - The corresponding function is Object()
69Regular Expression or Pattern Matching
70RegExp Objects
- An RegExp object corresponds to a regular
expression - Regular expressions were popular in Perl
JavaScript implementation is modeled on this
version - There are two syntax's for defining regular
expressions regexp1 new RegExp( "pattern )
// or regexp1 new RegExp( "pattern,flags
) regexp2 /pattern/flags // no quotes - Flags are g (match to all occurences) and i
(ignore case) - The latter literal version compiles the
pattern and is equivalent to - regexp2 regexp1.compile("pattern")
- Compilation is done for efficiency
- The RegExp object has two other methods
exec(str) and test(str)and we can also invoke
regular expression processing using new String
object methods
71RegExp Objects -- Examples
- Here are two examples function isDigit( str )
var regexp /0-9/ return
regexp.test( str ) function isSSN( str )
// match 999999999 or 999-99-9999 var
regexp /(\d9\d3-\d2-\d4)/
return regexp.test( str )
72RegExp Objects -- String Methods
- String object methods have been added to
JavaScript 1.2 to handle regular expressions --
consider an ordinary string ordstr - ordstr.search( regexp ) // like test()and
equivalent to ordstr m/regexp/ in
PERL returns true or false - ordstr.match( regexp ) // like exec()and
returns a results array as described for exec - newstr oldstr.replace( regexp, newsubstr ) //
equivalent to ordstr s/regexp/newsubstr/ in
PERL but returns a new string -- leaving original
unchanged - The split() method now takes a regular
expression as optional parameter - var strArray str.split( /\s\s/ )
- splits using surrounded by any whitespace
characters
73Simple Regular Expression Patterns
- Simple Single-character patterns are
- Single explicit character e.g. a
- dot . which matches ANY character except newline
\n - Character class is a Single-character pattern and
represented as a set c1c2c3...cN which matches
any one of the listed characters - ABCDE matches A B C D or E
- 0-9 is same as 0123456789
- a-zA-Z matches any lower or upper case letter
- Negated character class is represented by a carat
after left square bracket - 0-9 matches any character which is NOT a
digit 0 1 2 3 4 5 6 7 8 9 (there is another
critical use of -- see later) - There are a set of special character classes
shown overleaf such as \w which is equivalent to
A-Za-z0-9_.
74Regular Expressions -- Special Characters
\b backspace
\S Not a White Space
\b Word Boundary
\t tab
\B NOT a Word Boundary
\v vertical tab
\cC Control Character C
\w Any word Character
\d Matches a digit
\W Not a word Character
\D Matches a NON digit
\\ Backslash itself
\f Form Feed
\n (n integer) nth () selected as in n
\n New Line
\ooctal Char with this octal rep
\r Carriage Return
\xhex Char with this hex rep
. Anything
\s White Space \f\n\r\t\v
75Grouping Patterns in Regular Expressions
- Sequence is c1c2c3.. -- a sequence of single
characters - or 0, is "zero or more" of previous character
- or 1, is "one or more" of previous character
- ? or 0,1 is "zero or one" of previous character
- All matching is greedy -- they maximize number of
characters "eaten up" starting with leftmost
matching - Curly Brace Notation
- cn1,n2 means from n1 to n2 instances of
character c - cn1, means n1 or more instances of
character c - cn1 means exactly n1 instances of
character c - c0,n2 means n2 or less instances of character
c
76Alternation in Regular Expressions
- For single characters, alternates can be
specified by square brackets with - abc meaning a or b or c
- For general strings one can use to represent
alternatives or so that above example can also be
written - abc means a or b or c but this operator can be
generalized to longer sequences so that
instructors of this class can be written as - MarkowskiPodgornyBeca or, if you can't spell
Polish names - Markowsk(iy)Podgorn(yi)Be(ck)a
77Anchoring in Regular Expressions
- Patterns can be Anchored in four ways
- /Keyname/ matches to Keyname ONLY if it starts
string -- only has this special meaning at
start of regular expression - /Quit/ matches Quit ONLY if it ends string --
only has this meaning if at end of regular
expression - \b matches a word(PERL/C variable) boundary so
that - /Variable\b/ matches Variable but not Variables (
inside construct, \b means a backspace as
described in earlier table) - \B matches NOT a word boundary so that
- /Variable\B/ matches Variables but not Variable
78Parentheses in Regular Expressions
- Parentheses can be used as "memory" for relating
different parts of a match or for relating
substitution to match - If a part of a regular expression is enclosed in
parentheses, the MATCHED value is stored in
temporary variables \1 \2 .. for first,second ..
set of parentheses - /apple(,)\sorange\1/ matches apple,orange, in
apple,orange, cherry,peach. - Note ONLY use \1 \2 etc. in pattern. Use 1 2
(static properties of RegExp object) outside
pattern - re1 /Geoffrey(.)Fox/ when matched to str
Geoffrey Charles Fox stores - \1 ' Charles ' which can be transferred to
substitution string (via newstr
str.replace(re1,re2)) which could be - re2 /Geoffrey \(1\) Fox/ for result
Geoffrey(Charles)Fox - Parentheses can also be used to clarify meaning
of a regular expression by defining precedence of
a set of operations and so distinguish for
instance - /(ab)/ from /a(b)/
- There is a definite convention for precedence,
but as usual we recommend using parentheses
79The Backslash \ Operator
- When using the constructor function, the normal
string escape rules (preceding special characters
with \ when included in a string) are necessary.
For example, the following are equivalent - re new RegExp("\\w")
- re /\w/
- For characters that are usually treated
literally,\ indicates that the next character is
special and not to be interpreted literally. - For example, /b/ matches the character b. By
placing a backslash in front of b, that is by
using /\b/, the character becomes special to mean
match a word boundary. - While for characters that are usually treated
specially, \ indicates that the next character is
not special and should be interpreted literally. - For example, is a special character that means
0 or more occurrences of the preceding character
should be matched - For example, /a/ means match 0 or more a's.
- To match literally, precede the it with a
backslash - For example, /a\/ matches a.
80Static Properties of RegExp Object I
- RegExp.input or RegExp._ is text which we are
comparing regular expression with - It is set automatically in some circumstances
(e.g. when event handler for Form text field
called as in example below) - ltSCRIPT LANGUAGE"JavaScript1.2"gt
- function getInfo()
- re /(\w)\s(\d)/
- re.exec()
- window.alert(RegExp.1 ", your age is "
RegExp.2) - lt/SCRIPTgt
- Enter your first name and your age, and then
press Enter. - ltFORMgt
- ltINPUT TYPE"TEXT" NAME"NameAge"
onChange"getInfo(this)"gt - lt/FORMgt
81Static Properties of RegExp Object II
- RegExp.multiline if true, search through newlines
- RegExp. or RegExp.leftContext is part of
searched string before matched part - RegExp. or RegExp.lastMatch is part of searched
string that is matched to by regular expression - RegExp. or RegExp.rightContext is part of
searched string after matched part - So, the string searched is RegExp.leftContext
RegExp.lastMatch RegExp.rightContext - RegExp.lastParen The last parenthesized substring
match, if any - RegExp.1,2 .. 9 are the first through ninth
parenthesized expressions matched
82Regular Expression Examples
- /\s0(1)/ matches "white space", followed by zero
and 1 or more ones -- the set of ones is stored
in \1 ( 1) - /0-9\.0\D/ matches "the answer is 1.0 exactly"
but not "The answer is 1.00". - In first case is "the answer is ", is "1.0
" and ' is "exactly" - /a.c.d/ matches "axxxxcxxxxcdxxxxd" with and
' as null and as full string - /(a.b)c.d/ matches "axxxxbcxxxxbd" with
- \1 as "axxxxb" -- note backtracking as greedy
(a.b) first matches to "axxxxbcxxxxb" but then
tries again when following c.d fails to match
83Examples of Replace and test
- ltSCRIPT LANGUAGE"JavaScript1.2"gt
- re /(\w)\s(\w)/
- str "John Smith"
- newstrstr.replace(re, "2, 1")
- document.write(newstr)
- lt/SCRIPTgt // Prints out Smith, John
- Suppose re is a RegExp object and str a string,
then - function testinput(re, str)
- if (re.test(str))
- midstring " contains "
- else
- midstring " does not contain "
- document.write (str midstring re.source)
-
- Prints out a summary of matching result
84Examples of match (string) and exec (RegExp)
- //Match one d followed by one or more b's
followed by one d - //Remember matched b's and the following d
- myRe/d(b)(d)/ig str "cdbBdbsbz"
- myArray myRe.exec( str )
- myArray.index Index of First Character Matched
i.e. 1 - myArray.input The original String i.e. cdbBdbsbz
- myArray0 The characters matched i.e. dbBd
- myArray1 The first parenthesis i.e. bB
- myArray2 The second parenthesis i.e. d
- The static properties of RegExp are set including
1 2 lastMatch lastParen - Properties source lastIndex multiline global
ignoreCase of myRe are also set - Can also use myArray str.match(myRe)
85Multiple Calls to exec Method
- If your regular expression uses the g flag, you
can use the exec method multiple times to find
successive matches in the same string. When you
do so, the search starts at the substring of str
specified by the regular expression's lastIndex
property. For example, assume you have this
script - ltSCRIPT LANGUAGE"JavaScript1.2"gt
- myRe/ab/g
- str "abbcdefabh"
- myArray myRe.exec(str)
- document.writeln("Found " myArray0 ". Next
match starts at " myRe.lastIndex) - mySecondArray myRe.exec(str)
- document.writeln("Found " mySecondArray0 ".
Next match starts at " myRe.lastIndex) - lt/SCRIPTgt
- This script displays the following text
- Found abb. Next match starts at 3
- Found ab. Next match starts at 9
86String Objects
- String objects are created as in var myStr
new String(EECS")or more simply with var
myStr EECS" - Actually, the latter is a string literal, but
these are automatically converted as needed - String characters are indexed starting with 0
- The String object has one property var n
myStr.length
87String Methods
- Core JavaScript String methods
- charAt( pos )
- charCodeAt( pos )
- indexOf( searchstring, pos )
- lastIndexOf( searchstring, pos )
- split( separator )
- substring( start, end )
- toLowerCase() and toUpperCase()
- Static method String.fromCharCode()
88String Methods (contd)
- Client-side JavaScript defines more than a dozen
String methods (discussed later) - Six new methods added in JavaScript 1.2
- concat( string2 )
- match( regexp )
- replace( regexp, newSubstr )
- search( regexp )
- slice( begSlice, endSlice )
- substr( start, length )
89JavaScript Events
90Events
- Events are associated with
- forms
- hyperlinks
- images and image maps
- loading and unloading of documents
- input focus of a window or form element
- JavaScript introduces event handlers to handle
these events
91Event Handlers
92Event Handlers (contd)
93Event Handlers (contd)
- JavaScript 1.2 adds ten new event handlers
- Three existing handlers (onClick, onMouseOut, and
onMouseOver) have new properties - All these events are supported by IE4.0 except
onDragDrop
94Event Handler Examples
- The onLoad event handler is triggered when a page
is loaded or reloaded ltBODY
onLoad"init()"gtSimilarly, the onUnload handler
is called when a page is exited - Heres another example
- ltFORM
- onSubmit"return check(this)"gt
- ...
- lt/FORMgt
95Event Object
- An Event object (new in JavaScript 1.2) is passed
to an event handler when an event occurs - There are 23 types of events, one for each
handler for example, a Click event is passed to
the onClick handler when a link or form element
is clicked - An Event object has up to 11 properties
96Event Object (contd)
- Properties of an Event object
- The Click object, for example, supports all but
the data property (note the X and Y
properties are undefined for button clicks)