It tS ft T h l i Internet Software Technologies JavaScript – part two JavaScript part two IMCNE IMCNE A.A. 2008/09 Gabriele Cecchetti Gabriele Cecchetti OBJECTS G. Cecchetti Internet Software Technologies 2
I t t S ft T h l iInternet Software TechnologiesJavaScript – part twoJavaScript part two
IMCNEIMCNEA.A. 2008/09
Gabriele CecchettiGabriele Cecchetti
OBJECTS
G. Cecchetti Internet Software Technologies 2
Is JavaScript object-oriented? (1/2)
It has objects which can contain data and methodsIt has objects which can contain data and methods that act upon that data.
Objects can contain other objectsObjects can contain other objects.
It does not have classes, but it does have hi h d h l d i l diconstructors which do what classes do, including
acting as containers for class variables and h dmethods.
It does not have class-oriented inheritance, but it does have prototype-oriented inheritance.
G. Cecchetti Internet Software Technologies 3
Is JavaScript object-oriented? (2/2)
The two main ways of building up object systemsThe two main ways of building up object systems are by inheritance (is-a) and by aggregation (has-a) JavaScript does both but its dynamic naturea). JavaScript does both, but its dynamic nature allows it to excel at aggregation.
Objects cannot have private variables and privateObjects cannot have private variables and private methods: all members are public.
B J S i t bj t h i tBut JavaScript objects can have private variables and private methods.
G. Cecchetti Internet Software Technologies 4
Hashtables
To create a new hashtable and to assign it to a localTo create a new hashtable and to assign it to a local variable, just write:var myHashtable=();y ()
Then to add, replace or retreve elements in the hashtable you can write:myHashtable[name]=“A name”
The same operation can be written in a more efficient pnotation:myHashtable.name=“A name”;
The dot notation can be used when the subscript is a string constant in the form of legal identifier (not use keywords for
!)names!).
G. Cecchetti Internet Software Technologies 5
Hashtables === Objects !!
In JavaScript Objects and Hashtables are theIn JavaScript, Objects and Hashtables are the same thing, so:var myHashtable {};var myHashtable = {};
andvar myHashtable = new Object();
are equivalent.q
G. Cecchetti Internet Software Technologies 6
JavaScript is fundamentally about objects
Arrays are objectsArrays are objects.
Functions are objects.
OObjects are objects.
So what are objects? Objects are collections of name-value pairs.
The names are strings, and
the values are strings, numbers, booleans, and objects (including arrays and functions)
Objects are usually implemented as hashtables soObjects are usually implemented as hashtables so values can be retrieved quickly.
G. Cecchetti Internet Software Technologies 7
Object Constructors
Objects can be produced by constructors whichObjects can be produced by constructors, which are functions which initialize objects.
Constructors provide the features that classesConstructors provide the features that classes provide in other languages, including static variables and methodsvariables and methods.
Syntax:function Container(param) {
this.member = param;}
G. Cecchetti Internet Software Technologies 8
Object instance
S if t t bj tSo, if we construct a new object
var myContainer = new Container('abc');
then
myContainer is the reference to the object istance, and
myContainer member is a object member whichmyContainer.member is a object member which
contains 'abc'.
G. Cecchetti Internet Software Technologies 9
Public members of an object
The members of an object are all public membersThe members of an object are all public members.
Any function can access, modify, or delete those members or add new membersmembers, or add new members.
In our example:myContainer.member is a public member.
G. Cecchetti Internet Software Technologies 10
Example: defining an Object
function Car (b,m, c, e) {, , ,this.brand= b; // public memberthis.model=m; // public member
//this.color=c; // public memberthis.engine=e; // public memberthis display=fun(b); // public methodthis.display=fun(b); // public method}
function fun(s) {return “This is a “ + s
}
11G. Cecchetti Internet Software Technologies
Example: creating Object istances
Ferrari2008 = new Car(“Ferrari”,”F2009”, “red”);( , , )
Ferrari2009 = new Car(“Ferrari”,”F2004”, “red”, {“v10”,10});
i3000 C (“ i)Ferrari3000 = new Car(“Ferrari);
FerrariEmpty = new Car(); // members are undefined!
G. Cecchetti Internet Software Technologies 12
Example: initializing an object
In the object literal notation an object description isIn the object literal notation, an object description is a set of comma-separated name/value pairs inside curly bracescurly braces.
The names can be identifiers or strings followed by a colon they cannot use reserved JavaScript keywordscolon, they cannot use reserved JavaScript keywords.
The values can be literals or expressions of any type.
Example:Example:var FerrariX = { brand: "Ferrari", color: 'red'}
G. Cecchetti Internet Software Technologies 13
Example: add new members to an object
Look at this example:Look at this example:FerrariX.driver = "Michael Shumacher"
Driver was not present in the constructor.
JavaScript let you to add members at any time by assignment.
G. Cecchetti Internet Software Technologies 14
Public methods
If a value is a function we can consider it aIf a value is a function, we can consider it a method.
When a method of an object is invoked, the this i bl i h bjvariable is set to the object.
The method can then access the instance variables through the this variable.g
G. Cecchetti Internet Software Technologies 15
Private members of an object (1/3)
Private members are made by the constructorPrivate members are made by the constructor.Ordinary vars and parameters of the constructor becomes the private membersbecomes the private members.
Example:
function Container(param) {this.member = param; // public member
//var secret = 3; // private varvar that = this; // private var
}}
param, secret and that are 3 private instance i bl Th tt h d t th bj tvariables. They are attached to the object,
G. Cecchetti Internet Software Technologies 16
Private members of an object (2/3)
param secret and that are attached to theparam, secret and that are attached to the object but they are not accessible to the outside, nor are they accessible to the object's own publicnor are they accessible to the object s own public methods.
They are accessible to private methodsThey are accessible to private methods.
G. Cecchetti Internet Software Technologies 17
Private members of an object (3/3)
Private methods are inner functions of the constructorPrivate methods are inner functions of the constructor. Example:
function Container(param) {function Container(param) {function dec() { // private method
if (secret > 0) {secret -= 1;
return true;
} else { return false;} else { return false;}
}
this.member = param;
var secret = 3;
var that = this; // private parametervar that = this; // private parameter } // which references the object
G. Cecchetti Internet Software Technologies 18
Privileged methods of an object (1/2)
Private methods cannot be called by publicPrivate methods cannot be called by public methods.
To make private methods useful we need toTo make private methods useful, we need to introduce a privileged method.
A i il d h d i bl h iA privileged method is able to access the private variables and methods, and is itself accessible to h bli h d d h idthe public methods and the outside.
It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.
G. Cecchetti Internet Software Technologies 19
Privileged methods of an object (2/2)Privileged methods are assigned with this within the constructor.
Example if we extend the previous example:function Container(param) {
function dec() { … }
…
a that thisvar that = this; this.service = function () { // privileged method
if (dec()) {
return that.member; // return private
} else { // member valuereturn null;return null;
}
};};
}
G. Cecchetti Internet Software Technologies 20
What will happen running that program ?
Calling myContainer service() will returnCalling myContainer.service() will return 'abc' the first three times it is called.
After that it will return nullAfter that, it will return null.
service calls the private dec method which th i t i blaccesses the private secret variable.
Serviceis available to other objects and methods, but
it does not allow direct access to the private members.p
G. Cecchetti Internet Software Technologies 21
Closures
This pattern of public private and privilegedThis pattern of public, private, and privileged members is possible because JavaScript has closuresclosures.
What this means is that an inner function always has access to the vars and parameters of its outerhas access to the vars and parameters of its outer function, even after the outer function has returned.
P i t d i il d b l bPrivate and privileged members can only be made when an object is constructed.
Public members can be added at any time.
G. Cecchetti Internet Software Technologies 22
Objects properties can be enumerated (1/2)
Syntax:Syntax:for (variable in object) {
statementsstatements}
E lExample:for (var n in FerrariX) {
if (FerrariX.hasOwnProperty(n)) {
document.writeln("<p>" + n + ": "/+ myHashtable[n] + "</p>");
}}}
G. Cecchetti Internet Software Technologies 23
Objects properties can be enumerated (1/2)
The result will be:The result will be:<p>brand: Ferrari</p>
/<p>color: red</p>
<p>driver: Michael Shumacher</p>
G. Cecchetti Internet Software Technologies 24
A simple way to manipulate object members: with
Syntax:Syntax:with (object) {
statements
}
Examplewith (Ferrari) {( ) {
driver = ”Kimi Raikkonen”;
}}
Updates the driver member.
G. Cecchetti Internet Software Technologies 25
Putting members in a new object
There are two main ways of putting members in aThere are two main ways of putting members in a new object:
In the constructor (as seen some slides before)In the constructor (as seen some slides before)
In the prototype (next slide)This technique is usually used to add public methodsThis technique is usually used to add public methods.
G. Cecchetti Internet Software Technologies 26
Dynamic extension of object properties
The prototype mechanism is used for inheritanceThe prototype mechanism is used for inheritance.
To add a method to all objects made by a constructor add a function to the constructor'sconstructor, add a function to the constructor's prototype with the syntax:
bj N N lobjectName.propertyName = value;
Examples:FerrariX.wheels=6 // add this member only to
FerrariX istance while
FerrariX.prototype.wheels=4
// add the member to the constructor and
27
its inherited by all Childs.
G. Cecchetti Internet Software Technologies
Object operators
new:new: objectName = new objectType (param1 [, param2] …[,paramn])
delete:delete objectName;
delete objectName.property;
delete objectName[index]
in:propertyNameorNumber in ObjectName
instanceof:objectName instanceof objectTypeobjectName instanceof objectType
this:this[.property]
28
y
G. Cecchetti Internet Software Technologies
Object Hierarchies
Built-in objectsBuilt-in objectsString
RegExpRegExp,
Array,
DateDate,
Math,
B lBoolean,
Number, and
F tiFunction
Client objects (referred to HTML elements)
29
Client objects follow tree hierarchy of the HTML DOM.
G. Cecchetti Internet Software Technologies
BUILT-IN OBJECTS
G. Cecchetti Internet Software Technologies 30
Built-in Objects
ArrayArray
Boolean
Date
String
NumberNumber
Math
RegExp
Function
G. Cecchetti Internet Software Technologies 31
Arrays - Introduction
Arrays in JavaScript are also hashtable objectsArrays in JavaScript are also hashtable objects.
This makes them very well suited to sparse array applicationsapplications.
When you construct an array, you do not need to d l ideclare a size.
Arrays grow automatically, much like Java vectors.
The values are located by a key, not by an offset.
This makes JavaScript arrays very convenient toThis makes JavaScript arrays very convenient to use, but not well suited for applications in numerical analysisnumerical analysis.
G. Cecchetti Internet Software Technologies 32
Arrays elements and index
Arrays are not typedArrays are not typed.
They can contain numbers, strings, booleans, objects functions and arraysobjects, functions, and arrays.
You can mix strings and numbers and objects in hthe same array.
You can use arrays as general nested sequences, much as s-expressions.
The first index in an array is usually zero.y y
G. Cecchetti Internet Software Technologies 33
Arrays and Objects
The main difference between objects and arrays isThe main difference between objects and arrays is the length property.
The length property is always 1 larger than theThe length property is always 1 larger than the largest integer key in the array.
Th kThere are two ways to make a new array:var myArray = [];
A A ()var myArray = new Array();
G. Cecchetti Internet Software Technologies 34
Array length
When a new item is added to an array and theWhen a new item is added to an array and the subscript is an integer that is larger than the current value of length then the length is changedcurrent value of length, then the length is changed to the subscript plus one.
This is a convenience feature that makes it easy toThis is a convenience feature that makes it easy to use a for loop to go through the elements of an arrayarray.
G. Cecchetti Internet Software Technologies 35
Arrays
Syntax:Syntax:arrayObjectName = new Array(element0, element1, ..., elementN)
arrayObjectName = new Array(arrayLength)y j y( y g )
arrayObjectName = [element0,element1,element2,….,elementN];
Example:pcolors = new Array(3);
colors[0] = ”red”;
colors[1] = ”yellow”;
colors[2] = ”green”;
36G. Cecchetti Internet Software Technologies
Arrays literal notation
It’s similar to that for objectsIt s similar to that for objects.myList = ['oats', 'peas', 'beans', 'barley'];
emptyArray = [];
month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
slides = [slides = [{url: 'slide0001.html', title: 'Looking Ahead'},{url: 'slide0008.html', title: 'Forecast'},{ l ' lid 0021 ht l' titl 'S '}{url: 'slide0021.html', title: 'Summary'}
];
A new item can be added to an array by assignmentA new item can be added to an array by assignment.a[i + j] = f(a[i], a[j]);
G. Cecchetti Internet Software Technologies 37
Array example (1/2)
<html><head><titl >A Obj t l </titl >
function reverse() {<title>Array Object example</title><script type=“text/JavaScript”><!--var myarray1= new
myarray1.reverse();printArray(myarray1,"reversing");
}f ti hift() {
y yArray("1","2","3");
printArray(myarray1,"Starting array");
function add() {
function shift() {myarray1.shift();printArray(myarray1,"shifting ");
}function add() {myarray1[myarray1.length] =document.forms[0].text1.value;printArray(myarray1,"adding ");
}function printArray(arr,comment) {
for (var i=0; i<arr.length; i++)document writeln(arr[i]);printArray(myarray1, adding );
}function join() {
myarray2=myarray1.join("+");
document.writeln(arr[i]);document.writeln("<br>"+ comment);
}y y y y j ( );printArray(myarray2,"joining ");
}
}// --></script></head>
38G. Cecchetti Internet Software Technologies
Array example (2/2)
<body><form>Insert new element<input type="text" name="text1"><br>p yp<input type="button“ value="Insert" onClick="add()"> <br><input type="button" value="Join with + separator“ onClick="join()"><br><input type="button" value="Reverse" onClick="reverse()"><br><input type button value Reverse onClick reverse() ><br><input type="button" value="Shift " onClick="shift()"><br></body></html></html>
39G. Cecchetti Internet Software Technologies
Boolean objectThe Boolean object is an object wrapper for a boolean (true or false) value.
You can explicitly define a Boolean via:new Boolean([value])
where the Value is the initial value of the Boolean object. Note that:
the value is converted to a boolean value if necessarythe value is converted to a boolean value, if necessary
If value is: not specified, 0, -0, null, false, NaN, undefined, or the empty string (""), the object is set to false. All other values, including any object or the string "false", create an object with a value of true.
Example://var guess = new Boolean(false) //false value
var guess = new Boolean(0) //false value
var guess = new Boolean(true) //true valuevar guess new Boolean(true) //true value
var guess = new Boolean("whatever") //true value
G. Cecchetti Internet Software Technologies 40
Boolean object: properties
constructor Specifies the function that createdconstructor Specifies the function that created the object's prototype.
prototype Allows you to define properties onprototype Allows you to define properties on the Boolean that is shared by all Boolean objects.
G. Cecchetti Internet Software Technologies 41
Boolean object: methods
toString() Returns a string specifying the value oftoString() Returns a string specifying the value of the Boolean, in this case, "true" or "false."
valueOf() Returns the primitive value of a BooleanvalueOf() Returns the primitive value of a Boolean object.
G. Cecchetti Internet Software Technologies 42
Date Objects
There are fours ways of instantiating a date object:There are fours ways of instantiating a date object:new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds) //most parameters here are optionalmilliseconds) //most parameters here are optional.
Not specifying causes 0 to be passed in.
Here are a few examples of instantiating a date:Here are a few examples of instantiating a date:today = new Date()
birthday = new Date("March 11, 1985 09:25:00")y ( , )
birthday = new Date(85,2,11)
birthday = new Date(85,2,11,9,25,0)
G. Cecchetti Internet Software Technologies 43
Data object property
constructor Returns a reference to the Dateconstructor Returns a reference to the Date function that created the object.
prototype Allows you to add properties andprototype Allows you to add properties and methods to the object
G. Cecchetti Internet Software Technologies 44
Date object methods: to get Date
getFullYear() Returns year in full 4 digit format (ie: 2004).g () y g ( )
getYear() Returns the year. Deprecated
getMonth() Returns the month. (Range is 0-11)!
getDate() Returns the day of the month (Range is 1-31)
getDay() Returns the day of the week (Range is 0-6).0=Sunday 1=Monday etc0 Sunday, 1 Monday, etc.
getHours() Returns the hour (Range is 0-23).
getMinutes() Returns the minutes. (Range is 0-59).
getSeconds() Returns the seconds. (Range is 0-59).
getMilliseconds() Returns the milliseconds. (Range is 0-999).
tTi () R t th b f illi d b tgetTime() Returns the number of milliseconds between 1/1/1970 (GMT) and the current Date object.
getTimezoneOffset() Returns the offset between GMT and local time, in g () ,minutes.
G. Cecchetti Internet Software Technologies 45
Date object methods: to get UTC Date
getUTCFullYear() Returns the full 4 digit year in Universal time.g () g y
getUTCMonth() Returns the month in Universal time.
getUTCDate() Returns the day of the month in Universal time.
getUTCDay() Returns the day of the week in Universal time.
getUTCHours() Returns the hour in Universal time.
getUTCMinutes() Returns the minutes in Universal timegetUTCMinutes() Returns the minutes in Universal time.
getUTCSeconds() Returns the seconds in Universal time.
getUTCMilliseconds() Returns the milliseconds in Universal time.g ()
G. Cecchetti Internet Software Technologies 46
Date Object methods: to set Date
setFullYear(year, [month], [day]) Sets the year (4 digit) of the Date object.(y , [ ], [ y]) y ( g ) j
setYear(year) Sets the year of the Date object. Deprecated
setMonth(month, [day]) Sets the month [0-11].
setDate(day_of_month) Sets the day of the month [1-31].
setHours(hours, [minutes], [seconds], [millisec]) Sets the hour [0-23].
setMinutes(minutes [seconds] [millisec]) Sets the minutes [0 59]setMinutes(minutes, [seconds], [millisec]) Sets the minutes [0-59].
setSeconds(seconds, [millisec]) Sets the seconds [0-59].
setMilliseconds(milli) Sets the milliseconds [0-999].( ) [ ]
setTime(milli) Sets the value of the Date object in terms of milliseconds elapsed since 1/1/1970 GMT.
G. Cecchetti Internet Software Technologies 47
Date Object methods: to set UTC Date
setUTCFullYear(year, [month], [day]) (y , [ ], [ y])Sets the year of the Date object in Universal time.
setUTCMonth(month, [day]) Sets the month.
tUTCD t (d f th) S t th d f th thsetUTCDate(day_of_month) Sets the day of the month.
setUTCHours(hours, [minutes], [seconds], [millisec]) Sets the hours.
setUTCMinutes(minutes [seconds] [millisec]) Sets the minutessetUTCMinutes(minutes, [seconds], [millisec]) Sets the minutes.
setUTCSeconds(seconds, [millisec]) Sets the seconds.
setUTCMilliseconds(milli) Sets the milliseconds.
G. Cecchetti Internet Software Technologies 48
Date Objects methods: converting Date
toGMTString() Converts a date to a string,g() g,using the GMT conventions. Deprecated.
toLocaleString() Converts a date to a string,using current locale conventionsusing current locale conventions.
toLocaleDateString() Returns the date portion of the Date as a string,using current locale conventions.
toLocaleTimeString() Returns the time portion of the Date as a string,using current locale conventions.
toString() Converts a Date to human readable stringtoString() Converts a Date to human-readable string.
toUTCString() Converts a Date to human-readable string, in Universal time.
G. Cecchetti Internet Software Technologies 49
Data objects: other methods
parse(datestring) Returns the number of milliseconds in a date p ( g)string since 1/1/1970. (datestring: a string containing the date/time to be parsed).
UTC(year month [day] [hours] [minutes] [seconds] [milli]) ReturnsUTC(year, month, [day], [hours], [minutes], [seconds], [milli]) Returns the number of milliseconds in a date string since 1/1/1970, Universal time.
valueOf() Converts a Date to milliseconds. Same as getTime();.
G. Cecchetti Internet Software Technologies 50
Date objects: examples (1/2)
To write out today's date for example you would do:To write out today s date for example, you would do:<script type="text/javascript">
var mydate= new Date()h d ll ()var theyear=mydate.getFullYear()
var themonth=mydate.getMonth()+1var thetoday=mydate.getDate()
document.write("Today's date is: ")document.write(theyear+"/"+themonth+"/"+thetoday)y y
</script>
Output:pToday's date is: 2008/12/11
G. Cecchetti Internet Software Technologies 51
Date objects: examples (2/2)
Calculate day of week of a dateCalculate day of week of a datebirthday = new Date(1978,2,11)
weekday = birthday.getDay()weekday birthday.getDay()
alert(weekday)
//alerts 6, or Saturday
Set date to be a future datevar today=new Date()y ()
today.setDate(today.getDate()+3)
//today now is set to be 3 days into the future
G. Cecchetti Internet Software Technologies 52
String Object
The String object of JavaScript allows you toThe String object of JavaScript allows you to perform manipulations on a stored piece of text, such as extracting a substring searching for thesuch as extracting a substring, searching for the occurrence of a certain character within it etc.
Syntax for creating a String object:Syntax for creating a String object:var myStr = new String(string);
G. Cecchetti Internet Software Technologies 53
String Object properties
The string object has three properties and several methods:The string object has three properties and several methods:constructor : A reference to the function that created the object
length : Returns the number of characters in a string
prototype : Allows you to add properties and methods to the object
Example:<script type="text/javascript">
var txt="Hello World!"; document.write(txt.length);document.write(txt.length);
</script>
The output of the code above will be:p12
G. Cecchetti Internet Software Technologies 54
String Object methods (1/2)
anchor(name) Returns the string with the tag <A name="name"> surrounding it.( ) g g g
big() Returns the string with the tag <BIG> surrounding it.
blink() Returns the string with the tag <BLINK> surrounding it.
bold() Returns the string with the tag <B> surrounding itbold() Returns the string with the tag <B> surrounding it.
fixed() Returns the string with the tag <TT> surrounding it.
fontcolor(color) Returns the string with the tag <FONT color="color"> surround. it.
fontsize(size) Returns the string with the tag <FONT size="size"> surround. it.
italics() Returns the string with the tag <I> surrounding it.
link(url) Returns the string with the tag <A href="url"> surrounding itlink(url) Returns the string with the tag <A href url > surrounding it.
small() Returns the string with the tag <SMALL> surrounding it.
strike() Returns the string with the tag <STRIKE> surrounding it.
b() R t th t i ith th t SUB di itsub() Returns the string with the tag <SUB> surrounding it.
sup() Returns the string with the tag <SUP> surrounding it.
G. Cecchetti Internet Software Technologies 55
String methods: charAt and charCodeAt(x)
charAt(x) Returns the character at the "x" position withincharAt(x) Returns the character at the x position within the string.
Example: in the string "Hello world!", we will return the p g ,character at position 1:
<script type="text/javascript">
var str="Hello world!";
document.write(str.charAt(1));
</script></script>
The output of the code above will be:ee
charCodeAt(x) Returns the Unicode value of the character at position "x" within the string. Previous example using pos o e s g e ous e a p e us gcharCodeAt(x) is: 101
G. Cecchetti Internet Software Technologies 56
String methods: concat(v1, v2,...)
concat(v1, v2,...) Combines one or more strings (argumentsconcat(v1, v2,...) Combines one or more strings (arguments v1, v2 etc) into the existing one and returns the combined string. Original string is not modified.
Example
In the following example we will create two stringsIn the following example we will create two strings and show them as one using concat():
<script type="text/javascript">script type text/javascriptvar str1="Hello ";var str2="world!"; document.write(str1.concat(str2));
</ i t></script>
The output of the code above will be:Hello world!Hello world!
G. Cecchetti Internet Software Technologies 57
String methods: fromCharCode(c1, c2,...)
fromCharCode(c1, c2,...) Returns a string created by usingfromCharCode(c1, c2,...) Returns a string created by using the specified sequence of Unicode values (arguments c1, c2 etc). Method of String object, not String instance.
G. Cecchetti Internet Software Technologies 58
String methods: indexOf(substr, [start])
indexOf(substr, [start]) Searches and (if found) returnsindexOf(substr, [start]) Searches and (if found) returns the index number of the searched character or substring within the string. If not found, -1 is returned. "Start" is an optional argument specifying the position within string to begin the search. Default is 0.E l ill d diff t h ithiExample: we will do different searches within a "Hello world!" string:
<script type="text/javascript"><script type="text/javascript">var str="Hello world!";document.write(str.indexOf("Hello") + " ");d i ( i d Of(" ld") " ")document.write(str.indexOf("World") + " "); document.write(str.indexOf("world")); </script>
The output of the code above will be:The output of the code above will be:0 -1 6
G. Cecchetti Internet Software Technologies 59
String methods: lastIndexOf(substr, [start])
lastIndexOf(substr, [start]) Searches and (if found)lastIndexOf(substr, [start]) Searches and (if found) returns the index number of the searched character or substring within the string. Searches the string from end to beginning. If not found, -1 is returned. "Start" is an optional argument specifying the position within string to begin the search Default is string length 1begin the search. Default is string.length-1.
G. Cecchetti Internet Software Technologies 60
String methods: match(regexp)
match(regexp) Executes a search for a match within amatch(regexp) Executes a search for a match within a string based on a regular expression. It returns an array of information or null if no match is found.
Example: we will do different searches within a "Hello world!" string:
<script type="text/javascript">var str="Hello world!"; document.write(str.match("world") + " "); ( ( ) )document.write(str.match("World") + " "); document.write(str.match("worlld") + " "); document.write(str.match("world!")); </script>document.write(str.match( world! )); </script>
The output of the code above will be:world null null world!
G. Cecchetti Internet Software Technologies 61
String methods: replace(regexp,replacetext) replace(regexp, replacetext) Searches and replaces thereplace(regexp, replacetext) Searches and replaces the
regular expression portion (match) with the replaced text instead.
Example: we will perform a global and case-insensitive match, and the word Microsoft will be replaced each time it is found, independent of upper and lower case characters:
<script type="text/javascript">
str="Abc ABC abc abC";str="Abc ABC abc abC"; document.write(str.replace(/abc/gi, "CDE"));
</script>
The output of the code above will be:CDE CDE CDE CDE
G. Cecchetti Internet Software Technologies 62
String methods: search(regexp)
search(regexp) Tests for a match in a string Itsearch(regexp) Tests for a match in a string. It returns the index of the match, or -1 if not found.
G. Cecchetti Internet Software Technologies 63
String methods: extracting string portions
slice(start, [end]) Returns a substring of the string basedslice(start, [end]) Returns a substring of the string based on the "start" and "end" index arguments, NOT including the "end" index itself. "End" is optional, and if none is specified, the slice includes all characters from "start" to end of string.
substring(from, [to]) Returns the characters in a string between "from" and "to" indexes, NOT including "to" inself. "To" is optional, and if omitted, up to the end of the string is assumedassumed.
substr(start, [length]) Returns the characters in a string beginning at "start" and through the specified number ofbeginning at start and through the specified number of characters, "length". "Length" is optional, and if omitted, up to the end of the string is assumed.
G. Cecchetti Internet Software Technologies 64
Extracting string portions examples
Example:Example: <script type="text/javascript">
var str="Hello happy world!"; document.write(str.slice(7,11) + " ");
document.write(str.substring(7,12) + " ");
document write(str substr(7 5));document.write(str.substr(7,5));
</script>
The output of the code above will be:The output of the code above will be:Happy Happy Happy
G. Cecchetti Internet Software Technologies 65
String methods: split(delimiter, [limit])
split(delimiter, [limit]) Splits a string into many accordingsplit(delimiter, [limit]) Splits a string into many according to the specified delimiter, and returns an array containing each element. The optional "limit" is an integer that lets you specify the maximum number of elements to return.
Example: we will split up a string in different ways:<script type="text/javascript">
var str="How are you doing today?"; document.write(str.split(" ") + "<br>"); ( p ( ) )document.write(str.split("") + "<br>"); document.write(str.split(" ",3)); </script>
Th t t f th d b ill bThe output of the code above will be:How,are,you,doing,today?
H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
How,are,you
G. Cecchetti Internet Software Technologies 66
String methods: changing case letters
toLowerCase() Returns the string with all of its characterstoLowerCase() Returns the string with all of its characters converted to lowercase.
toUpperCase() Returns the string with all of its characters pp () gconverted to uppercase.
G. Cecchetti Internet Software Technologies 67