Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings, Math and Dates JavaScript. 2 Objectives How to modify strings with common string method When and how to use the Math Object How to use the Date.

Similar presentations


Presentation on theme: "Strings, Math and Dates JavaScript. 2 Objectives How to modify strings with common string method When and how to use the Math Object How to use the Date."— Presentation transcript:

1 Strings, Math and Dates JavaScript

2 2 Objectives How to modify strings with common string method When and how to use the Math Object How to use the Date Object

3 JavaScript 3 Introduction –The String, Math and Date are built in JavaScript Objects that are independent of the Document Object Model Formal Specifications for these objects are found in ECMA-262 recommendationsECMA-262 –European Computer Manufacturers Association (ECMA) –It acquired the name Ecma International in 1994

4 JavaScript 4 JavaScript String Object String Object –A string is any text inside a quote pair –A quote pair consists of either double or single quotes. This allows one string to nest inside another, as often happens with event handlers. –onclick = “alert(‘Hello all’)” –JavaScript imposes no practical limit on the number of characters that a string can hold. –Most older browser have a limit of 255 characters in length for a script statement. You may need to divide these lines into smaller chunks

5 JavaScript 5 JavaScript String Object You have two ways to assign a string value to a variable: –var myString = “Howdy”; –var myString = new String(“Howdy”); As of Navigator 3 and IE 4 Joining Strings –Bringing two strings together as a single string is called concatenation –The addition operator (+) links multiple strings together

6 JavaScript 6 JavaScript String Object Concatenation Example: var msg = “Four score”; msg = msg + “ and seven”; msg = msg + “ years ago.”; The pieces can be combinations of string literals (text inside quotes) or string variables.

7 JavaScript 7 JavaScript String Object The add-by-value operator (+=) provides a shortcut. var msg = “Four score”; msg += “ and seven”; msg += “ years ago”; You can also combine the operators if the need arises: var msg = “Four Score”; msg += “ and seven” + “ years ago”;

8 JavaScript 8 JavaScript String Object String Methods –The String object has the most diverse collection of methods associated with it (851-852). –To use a string method, the string being acted upon becomes part of the reference followed by the method name var result = string.methodName(); Changing String Case Methods –To convert to Uppercase var result = string.toUpperCase(); –To convert to Lowercase var result = string.toLowerCase();

9 JavaScript 9 JavaScript String Object These methods come in handy when your scripts need to compare strings that may not have the same case. –A string in a lookup table verses a string entered by a user –Because the methods don’t change the original strings attached to the expressions, you can simply compare the evaluated results of the methods.

10 JavaScript 10 JavaScript String Object var foundMatch = false; stringA = "test"; stringB = "TeST"; var stringC = “ ”; //Null string if (stringA.toUpperCase() = = stringB.toUpperCase()) foundMatch = true; document.write(foundMatch); stringC=stringA.toUpperCase(); document.write(" " + stringC) Produces: true TEST

11 JavaScript 11 JavaScript String Object String Searches –You can use the string.indexOf() method to see if one string is contained by another document.write(navigator.userAgent + " "); document.write(navigator.userAgent.indexOf("Windows")); Produces Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461; SV1;.NET CLR 1.1.4322) 35 If no match appears a value of -1 is returned. –You can use this fact to test if a string is nested in another string

12 JavaScript 12 JavaScript String Object Extracting copies of character and substrings –To extract or examine a single character at a know position within a string, use the charAt() method var stringA = “Building C”; var bldgLetter = stringA.charAt(9); //results would be the letter C –Another method, string.substring(), enables the extraction of a sequence of characters. –NOTE: The character at the ending position is not included in the extracted string. var stringA = “banana daiquiri”; var excerpt = stringA.substring(2, 6); //6-2 = 4 characters extracted //result: excerpt = “nana”; –The number 2 desiganted the straring position of the extracted string (index begins at zero) –The number 6 designates the number of charters to extract

13 JavaScript 13 JavaScript String Object Example var stringA = “The United States of America”; var excerpt = stringA.substring(stringA.indexOf(“ “) + 1, stringA.length); //result: excerpt = “United States of America” You can make your own string prototypes in JavaScript

14 JavaScript 14 JavaScript String Object JavaScript Prototype <!-- //core custom method for writing text backwards function outputbackwards(){ for (i=this.length-1;i>=0;i--) document.write(this.charAt(i)) } //Attach custom method to string object String.prototype.writeback=outputbackwards //--> // Test prototype var message1="Welcome to my site!" message1.writeback() //produces: !etis ym ot emocleW document.write(" "); var message2="Today is a beautiful day" message2.writeback() //produces: yad lufituaeb a si yadoT

15 JavaScript 15 JavaScript String Object Palindromes –A palindrome is a text string that reads the same from left to right and right to left. “12321 is a palindrome “racecar” is a palindrome “The car is big”is not a palindrome

16 JavaScript 16 JavaScript Math Object When you use the Math Object, JavaScript summons a single Math Object Properties and Methods. –One Math Object actually occurs per window or frame –Its referred to as a fixed or static object The Math Object with an Upper Case M is part of a reference to the property or method. –Properties are constant values, such as pi and the square root of 2

17 JavaScript 17 JavaScript Math Object Examples of the Math Object Properties –var piValue = Math.PI; –var rootOfTwo= Math.SQRT2;

18 JavaScript 18 JavaScript Math Object The Math Object Properties include: –Math.E E PropertyE Property euler's constant (the base for natural logarithms) –Math.LN2 LN2 PropertyLN2 Property The Natural Logarithm of 2 –Math.LN10LN10 PropertyLN10 Property The Natural Logarithm of 10 –Math.LOG2ELOG2E PropertyLOG2E Property The base 2 logarithm value of e

19 JavaScript 19 JavaScript Math Object –Math.LOG10ELOG10E PropertyLOG10E Property The base 10 logarithm value of e –Math.PIPI PropertyPI Property The value of PI –Math.SQRT1_2SQRT1_2 PropertySQRT1_2 Property The Square Root of 1/2 –Math.SQRT2SQRT2 PropertySQRT2 Property The Square Root of 2

20 JavaScript 20 JavaScript Math Object Math Object Methods cover a wide range of trigonometric functions and other math functions. –Math.abs(val)Absolute value of val –Math.acos(val)Arc cosine (in radians) of val –Math.asin(val)Arc sin (in radians) of val –Math.atan(val)Arc tangent (in radians) of val –Math.atan2(val1, val2) Angle of polar coordinates of x and y

21 JavaScript 21 JavaScript Math Object –Math.ceil(val) Next integer greater than or equal to val –Math.cos(val) Cosine of val –Math.exp(val) Euler’s constant to the power of val –Math.floor(val)Next integer less than or equal to val –Math.log(val)Natural logarithm (base e) of val –Math.max(val1,val2) The greater of val1 or val2 –Math.min(val1,val2) The lesser of val1 or val2 –Math.pow(val1,val2) val1 raised to the val2 power –Math.random()Random number between 0 and 1 –Math.round(val)N+1 when val >= n.5 otherwise n –Math.sin(val)Sine (in radians) of val –Math.sqrt(val)Square root of val –Math.tan(val)Tangent (in radians) of val

22 JavaScript 22 JavaScript Math Object Creating Random Numbers –The Math.random( ) method returns a floating point value between 0 and 1. –If you design a script to act like a card game, you need random integers between 1 and 52; for dice the range is 1 to 6 per die. <!-- document.write("Math.random()= " + Math.random() + " "); //--> Math.random()= 0.6457616348716495 Math.random()= 0.4368909728249476 Math.random()= 0.15361968190433417

23 JavaScript 23 JavaScript Math Object To generate a random number between zero and any top value, use the following formula. –Math.floor(Math.random() * n + 1) Here n is the top number (pg 885) documentwrite("Number between 0 and 5 = " + Math.floor(Math.random()* 6) + " "); document.write("Number between 0 and 5 = " + Math.floor(Math.random()* 6) + " "); Produces: Number between 0 and 5 = 5 Number between 0 and 5 = 3 Number between 0 and 5 = 4 Number between 0 and 5 = 0 Number between 0 and 5 = 2

24 JavaScript 24 JavaScript Math Object To generate random numbers between a different range (dice would use a range of 1 to 6), use this formula : –Math.floor(Math.random() * (n – m + 1)) + m Here m is the lowest possible integer value and n is upper value document.write("Dice Shake = " + Math.floor((Math.random() * 6) + 1) + " "); document.write("Dice Shake = " + Math.floor((Math.random() * 6) + 1) + " ”);- Produces: Dice Shake = 2 Dice Shake = 6 Dice Shake = 6 Dice Shake = 1

25 JavaScript 25 JavaScript Date Object A scriptable browser contains one global Date object per window. When you wish to work with a date, such as displaying today’s date, you need to invoke the Date object constructor function to obtain an instance of a Date object tied to a specific time and date. var today = new Date(); document.write(today); Produces: Sun Nov 19 19:26:35 EST 2006

26 JavaScript 26 JavaScript Date Object The Date object takes a snapshot of the PC’s internal clock and returns a Date object for that instance. –Internally the value of a Date object instance is the time in milliseconds, from zero o’clock on January 1 st, 1970 Greenwich Mean Time Zone. You can specify the date information as parameters to the Date object constructor var someDate = new Date("September 22, 1952 02:00:00");

27 JavaScript 27 JavaScript Date Object You can extract components of the Date object via a series of methods that you apply to a Date object instance. (table 10-1, pg 117) var today = new Date(); document.write("Milliseconds since 1/1/70 00:00:00 GMT: " + today.getTime()); document.write(" Current year: " + today.getYear()); document.write(" Current month: " + today.getMonth()); document.write(" Current date: " + today.getDate()); document.write(" Current day: " + today.getDay()); document.write(" Current hours: " + today.getHours()); document.write(" Settin time in ms: " + today.setTime(1000000000)); document.write(" Current year: " + today.getFullYear());

28 JavaScript 28 JavaScript Date Object Results Milliseconds since 1/1/70 00:00:00 GMT: 1163984366847 Current year: 2006 Current month: 10 (note getMonth is zero based i.e. Jan = 0, Feb = 1) Current date: 19 Current day: 0 (note getDay is zero based i.e. Sun = 0, Mon = 1) Current hours: 19 Settin time in ms: 1000000000 Current year: 1970

29 JavaScript 29 JavaScript Date Object Performing calculations with dates frequently requires working with the milliseconds values of the Date object. function nextWeek(){ var todayInMS = today.getTime(); var nextWeekInMS = todayInMS + ( 60 * 60 * 24 * 7 * 1000); return new Date(nextWeekInMS); } var today = new Date(); document.write(today + " "); document.write(nextWeek()); Produces Sun Nov 19 20:18:48 EST 2006 Sun Nov 26 20:18:48 EST 2006


Download ppt "Strings, Math and Dates JavaScript. 2 Objectives How to modify strings with common string method When and how to use the Math Object How to use the Date."

Similar presentations


Ads by Google