Top Banner
Strings, Math and Dates JavaScript
29

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.

Dec 18, 2015

Download

Documents

Lester Webster
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 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.

Strings, Math and Dates

JavaScript

Page 2: 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.

JavaScript 2

Objectives

• How to modify strings with common string method

• When and how to use the Math Object

• How to use the Date Object

Page 3: 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.

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 recommendations

– European Computer Manufacturers Association (ECMA)

– It acquired the name Ecma International in 1994

Page 4: 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.

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

Page 5: 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.

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

Page 6: 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.

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.

Page 7: 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.

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”;

Page 8: 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.

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();

Page 9: 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.

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.

Page 10: 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.

JavaScript 10

JavaScript String Objectvar 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("<br />" + stringC)

Produces:trueTEST

Page 11: 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.

JavaScript 11

JavaScript String Object

• String Searches– You can use the string.indexOf() method to see if

one string is contained by anotherdocument.write(navigator.userAgent + "<br />");

document.write(navigator.userAgent.indexOf("Windows"));

ProducesMozilla/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

Page 12: 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.

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

Page 13: 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.

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

Page 14: 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.

JavaScript 14

JavaScript String Object<title>JavaScript Prototype</title><script type="text/javascript"><!-- //core custom method for writing text backwardsfunction outputbackwards(){ for (i=this.length-1;i>=0;i--)document.write(this.charAt(i))}

//Attach custom method to string objectString.prototype.writeback=outputbackwards//--></script></head><body><script type="text/javascript"> // Test prototype var message1="Welcome to my site!" message1.writeback() //produces: !etis ym ot emocleW document.write("<br />"); var message2="Today is a beautiful day" message2.writeback() //produces: yad lufituaeb a si yadoT</script></body>

Page 15: 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.

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

Page 16: 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.

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

Page 17: 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.

JavaScript 17

JavaScript Math Object

• Examples of the Math Object Properties

– var piValue = Math.PI;

– var rootOfTwo= Math.SQRT2;

Page 18: 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.

JavaScript 18

JavaScript Math Object• The Math Object Properties include:

– Math.E E Property

• euler's constant (the base for natural logarithms)

– Math.LN2 LN2 Property

• The Natural Logarithm of 2

– Math.LN10 LN10 Property

• The Natural Logarithm of 10

– Math.LOG2E LOG2E Property

• The base 2 logarithm value of e

Page 19: 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.

JavaScript 19

JavaScript Math Object– Math.LOG10E LOG10E Property

• The base 10 logarithm value of e

– Math.PI PI Property

• The value of PI

– Math.SQRT1_2 SQRT1_2 Property

• The Square Root of 1/2

– Math.SQRT2 SQRT2 Property

• The Square Root of 2

Page 20: 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.

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

Page 21: 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.

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

Page 22: 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.

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.

<script language="JavaScript" type="text/javascript"><!--document.write("Math.random()= " + Math.random() + "<br />");document.write("Math.random()= " + Math.random() + "<br />");document.write("Math.random()= " + Math.random() + "<br />");//--></script>

Math.random()= 0.6457616348716495Math.random()= 0.4368909728249476Math.random()= 0.15361968190433417

Page 23: 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.

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) + "<br />");document.write("Number between 0 and 5 = " + Math.floor(Math.random()* 6) + "<br />");document.write("Number between 0 and 5 = " + Math.floor(Math.random()* 6) + "<br />");document.write("Number between 0 and 5 = " + Math.floor(Math.random()* 6) + "<br />");document.write("Number between 0 and 5 = " + Math.floor(Math.random()* 6) + "<br />");

Produces:

Number between 0 and 5 = 5Number between 0 and 5 = 3Number between 0 and 5 = 4Number between 0 and 5 = 0Number between 0 and 5 = 2

Page 24: 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.

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) + "<br />");

document.write("Dice Shake = " + Math.floor((Math.random() * 6) + 1) + "<br />");

document.write("Dice Shake = " + Math.floor((Math.random() * 6) + 1) + "<br />");

document.write("Dice Shake = " + Math.floor((Math.random() * 6) + 1) + "<br />”);-

Produces:

Dice Shake = 2Dice Shake = 6Dice Shake = 6Dice Shake = 1

Page 25: 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.

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

Page 26: 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.

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 1st, 1970 Greenwich Mean Time Zone.

• You can specify the date information as parameters to the Date object constructorvar someDate = new Date("September 22, 1952 02:00:00");

Page 27: 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.

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("<br /> Current year: " + today.getYear()); document.write("<br /> Current month: " + today.getMonth()); document.write("<br /> Current date: " + today.getDate()); document.write("<br /> Current day: " + today.getDay()); document.write("<br /> Current hours: " + today.getHours()); document.write("<br /> Settin time in ms: " + today.setTime(1000000000)); document.write("<br /> Current year: " + today.getFullYear());

Page 28: 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.

JavaScript 28

JavaScript Date Object

• Results

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

Page 29: 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.

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 + "<br />");

document.write(nextWeek());

ProducesSun Nov 19 20:18:48 EST 2006Sun Nov 26 20:18:48 EST 2006