Download presentation
Presentation is loading. Please wait.
Published byAmanda Gregory Modified over 9 years ago
1
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 sunny.shi@senecacollege.ca SENECA COLLEGE
2
22 Outline JavaScript Build-in Objects JavaScript Built-in/ Global objects: String Array Date Math Number Boolean Regular Expression Next Class: HTML
3
JavaScript Objects Built-in Objects/ Global Objects String Array Date Math Number Boolean Regular Expression User-defined Objects 3
4
4 String Object – property & methods String.length - returns the number of character in a string. String.charAt( index) - returns the character at the specific index. - index starts from 0. - var s = “hello”; alert(s[0]); String.charCodeAt(index) - returns the unicode of the character in place of character. - Unicode provides a unique number for every character, no matter what the platform is.
5
5 String Object - methods String.indexOf( substring) returns the position at which the character or string begins -1 means the character or string is not in the string. String.lastIndexOf( substring ) returns the position at which the last occurrence of your character or string. -1 means the character or string is not in the string.
6
6 String Object - methods String.substr(startIndex,subLength) returns a sub string, starting from startIndex with the length subLength e.g., var s= "abcdefg"; alert(s.substr(2,3)); // cde String.substring(startIndex,y) returns a sub string, starting from index startIndex (inclusive) ending at index y (not inclusive) e.g., var s= "abcdefg"; alert(s.substring(2,3)); //c
7
7 String Object - methods String.toLowerCase( ) converts a string to lowercase. String.toUpperCase( ) converts a string to uppercase.
8
String Object - methods String.replace(srchStr, repStr) – searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. E.g., var s="Hello all!"; var x=s.replace("all","ALL"); alert(x); Outpu: Hello ALL!
9
String.trim() – Trim white space from the beginning and the end String.trimLeft() – Trim white space from the left side String.trimRight() – Trim white space from the right side var s = " Good morning "; var n1 = s.length; var n2 = s.trim().length; alert(n1 + "-----"+ n2); 9 String Object - methods
10
var s= "Hello ALL!"; var len= s.length; alert("Length of " + s + " is " + len); alert("string is: "+s + "\n" + "charAt(2) is: "+ s.charAt(2) + "\n"+ "charCodeAt(6) is: " + s.charCodeAt(6) + "\n"+ "indexOf('l') is: " + s.indexOf('l')+ "\n" + "indexOf('all') is: " + s.indexOf('all')+ "\n" + "lastIndexOf('l') is: " + s.lastIndexOf('l')+ "\n" + "lastIndexOf('all') is: " + s.lastIndexOf('all')+ "\n" + "substr(2,4) is " + s.substr(2,4) + "\n" + "substr(2, 20) is " + s.substr(2,20)+ "\n" + "substring(2,4) is "+ s.substring(2,4) + "\n" + "substring(2,20) is " + s.substring(2, 20) + "\n" + "toLowerCase() is " + s.toLowerCase() + "\n" + "toUpperCase() is " + s.toUpperCase() + " \n" + "replace('ALL ! ', ' all ') is " + s.replace("ALL !", " all ") + "\n "+ "trim() is " + s.trim() );
11
Summary of String property/ functions var s = “Hello”; s.length s.charAt( index) s.charCodeAt(index) s.indexOf( substring) s.lastIndexOf(substring) s.substr(startIndex,subLength) s.substring(startIndex,y) s.toLowerCase( ) s.toUpperCase( ) s.replace(srchStr, repStr) s.trim() s.trimLeft() s.trimRight() 11
12
12 Array Object Index starts from 0. When dealing with arrays, defining an array assigning values (initializing) to an array accessing an array updating an array
13
13 Array Object Defining an array (1) var name_of_array = new Array(number_of_elements); var product = new Array(5); (2) var product= new Array("books","..","..","..","plates"); (3) var product = [“books”, "..","..","..","plates“]; (4) var product = []; Assigning values (initializing) to an array var product= new Array(5) product[0]="books"; product[1]="cars"; product[2]="cups"; product[3]="dishes"; product[4]="plates";
14
14 Array Object Accessing an array for (var x=0; x<product.length; x++) { alert(“No. " + x + " is " + product[x]); } Updating an array assign a new value to that occurrenece: product[3]=“cutlery”;
15
15 Array Object - Property Array.length property return the number of occurrences in an array (how many items in an array). alert(“the length of the array is " + product.length);
16
Array Object - methods Array.concat(arr1,arr2, …, arrN): Joins two or more arrays, and returns a copy of the joined arrays. var array1 = ["a1", "a2"]; var array2 = new Array(); array2[0] = "b0"; array2[1]="b1"; array2[2] = "b2"; var array3=["c1", "c2", "c3"] var con1 = array1.concat(array2, array3); alert(con1); alert(con1[3]); // b1 alert(con1.join()); alert(con1.join(" and "));
17
17 Array Object - methods Array.join( separator) Return a string, which joins all the elements of an array, separated by a specified string separator (if none is specified, the default is a comma). product.join(); product.join("*"); product.join(“ and "); product.join(" "); Array.toString(): Converts an array to a string, and returns the result. – var array1 = ["a1", "a2"]; alert(array1.toString()+"..."); // a1, a2…
18
Array.indexOf(elem): Search the array for an element and returns it's FIRST position, if not found, return -1. – var array1 = ["a1", "a2", "a1"]; alert(array1.indexOf("a1")); //0 Array.lastIndexOf(elem): Search the array for an element, starting at the end, and returns it's position. – var array1 = ["a1", "a2", "a1"]; alert(array1.lastIndexOf("a1")); // 2 Array Object - methods
19
Array.reverse(): Reverses the order of the elements in an array. – alert(array1.reverse().join()); Array.sort(): Sorts the elements of an array. – var array1 = ["ba1", "ca2", "a3"]; array1.sort(); alert(array1); Descending order ? Array Object - methods Sort & reverse
20
Array.pop(): Removes the last element of an array, and returns that element – var array1 = ["a1", "a2", "a3"]; var x = array1.pop(); alert(x); // a3 Array.push(new_Element): Adds new elements to the end of an array, and returns the new length. – var array1 = ["a1", "a2", "a3"]; var x = array1.push("a4"); alert(array1); alert(x); // 4 Array Object - methods
21
Array.shift(): Removes the first element of an array, and returns that element. – var array1 = ["ba1", "ca2", "a3"]; var x = array1.shift(); alert(x); // ba1 Array.unshift():Adds new elements to the beginning of an array, and returns the new length. – var array1 = ["ba1", "ca2", "a3"]; var x = array1.unshift("a5", "a6"); alert(x); // 5 alert(array1); // a5, a6, ba1, ca2, a3 Array Object - methods
22
Array.slice(start, end): returns the selected elements in an array, as a new array object. selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. Note: The original array will not be changed. – var array1 = ["ba1", "ca2", "a3"]; var x = array1.unshift("a5", "a6"); alert(array1); // a5, a6, ba1, ca2, a3 alert(array1.slice(1,3)); // a6, ba1 Array Object - methods
23
Summer of Array property/ functions Array.length Array.concat(arr1,arr2, …, arrN) Array.join( separator) Array.indexOf(elem): Array.lastIndexOf(elem): Array.reverse(): Array.sort(): Array.pop(): Array.push(new_Element): Array.shift(): Array.unshift(): Array.slice(start, end):
24
24 Date Object Getter getMonth() returns 0 through 11 - 0 = January getDate() returns 1 through 31 getDay() returns 0 through 6 - 0 = Sunday getFullYear() returns 4 digit year getHours() returns 0 through 23 getMinutes() returns 0 through 59 getSeconds() returns 0 through 59 getMilliseconds() returns 0 through 999 toLocaleString() returns the local date/time as a string. toGMTString() returns the GMt date/time as a string. GMT: Greenwich Mean Time
25
var d = new Date(); alert(d); alert("getMonth() = "+ d.getMonth()); alert("getDate() = "+ d.getDate()); alert("getDay() = "+ d.getDay()); alert("getFullYear() = "+ d.getFullYear()); alert("getHours() = "+ d.getHours()); alert("getTime()" + d.getTime()); alert("toLocaleString() = "+ d.toLocaleString()); alert("toGMTString()" + d.toGMTString()); Example:
26
26 Date Object Four ways of instantiating a date: new Date() // current date and time new Date(milliseconds) //milliseconds since 1970/01/01 new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds) today = new Date() var d1 = new Date("October 13, 1975 11:13:00") var d2 = new Date(79,5,24) var d3 = new Date(79,5,24,11,33,0) var d4 = new Date("2015/1/13 09:32");
27
27 Date Object setter setMonth() set month 0 through 11 - 0 = January setDate() set date of month 1 through 31 setDay() set day of week 0 through 6 - 0 = Sunday setFullYear() set 4 digit year setHours() set hours 0 through 23 setMinutes() set minutes 0 through 59 setSeconds() set seconds 0 through 59 setMilliseconds() set milliseconds 0 through 999
28
28 Date Object Example: new_date=new Date(); alert(new_date); new_date.setMonth(3); // 0 through 11 alert(new_date); new_date.setDate(10); // 1 through 31 alert(new_date); new_date.setFullYear(1989); // 4 digit year alert(new_date);
29
29 Date Object Compare two dates: Calculate the difference in Milliseconds var x=new Date(); x.setFullYear(2015,11,25); var today = new Date(); if (today<x) { alert("Today is before this year’s Christmas"); var y = x-today; alert("There are "+ y + "Milliseconds"); var k = y/1000/60/60/24; alert("There are "+ k + "days"); } else { alert("Today is after Christmas"); }
30
30 Math Object - Properties PropertyDescription EReturns Euler's number (approx. 2.718) LN2Returns the natural logarithm of 2 (approx. 0.693) LN10Returns the natural logarithm of 10 (approx. 2.302) LOG2EReturns the base-2 logarithm of E (approx. 1.442) LOG10EReturns the base-10 logarithm of E (approx. 0.434) PIReturns PI (approx. 3.14159) SQRT1_2Returns the square root of 1/2 (approx. 0.707) SQRT2Returns the square root of 2 (approx. 1.414) alert("Euler's number: " + Math.E);
31
31 MethodDescription abs(x)Returns the absolute value of x acos(x)Returns the arccosine of x, in radians asin(x)Returns the arcsine of x, in radians atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians atan2(y,x)Returns the arctangent of the quotient of its arguments ceil(x)Returns x, rounded upwards to the nearest integer cos(x)Returns the cosine of x (x is in radians) exp(x)Returns the value of E x floor(x)Returns x, rounded downwards to the nearest integer log(x)Returns the natural logarithm (base E) of x max(x,y,z,...,n)Returns the number with the highest value min(x,y,z,...,n)Returns the number with the lowest value pow(x,y)Returns the value of x to the power of y random()Returns a random number between 0 and 1 round(x)Rounds x to the nearest integer sin(x)Returns the sine of x (x is in radians) sqrt(x)Returns the square root of x tan(x)Returns the tangent of an angle Math Object Methods alert("abs: " + Math.abs(-6));
32
Number Object PropertyDescription MAX_VALUE Returns the largest number possible in JavaScript(1.7976931348623157e+308 ) MIN_VALUE Returns the smallest number possible in JavaScript (5e-324 ) NEGATIVE_ INFINITY Returns negative infinity (-Infinity) POSITIVE_I NFINITY Represents infinity (returned on overflow) NaNRepresent a “Not-a-Number” value (isNaN()) The Number object is an object wrapper for primitive numeric values. Number objects are created with new Number(). var num = new Number(value); If the value parameter cannot be converted into a number, it returns NaN (Not-a-Number). These properties can only be accessed as Number.MAX_VALUE.
33
Number Object - methods toFixed(x): – formats a number to a specified number (x) of digits after decimal point. – X is optional. Default is 0 (no digits after the decimal point). var num = new Number(13.3754); var a = num.toFixed(); // 13 var b = num.toFixed(2); // 13.38 var c = num.toFixed(3); // 13.375 var d = num.toFixed(6); // 13.375400 alert("= " + a + '\n' + b+ '\n'+c+ '\n'+d);
34
Number Object - methods toPrecision(x): – formats a number to a specified length (x). – A decimal point and nulls are added (if needed), to create the specified length. var num = new Number(13.3714); var a = num.toPrecision(); // 13.3714 var b = num.toPrecision(2); // 13 var c = num.toPrecision(3); // 13.4 var d = num.toPrecision(10); // 13.37140000 alert("= " + a + '\n' + b+ '\n'+c+ '\n'+d);
35
Number Object - Methods valueOf() :return the primitive value of a Number object. var num = 15; var n = num.valueOf();
36
Number Object - methods toString(radix): converts a Number object to a string. var num = 15; var a = num.toString() //15 var b = num.toString(2); // 1111 var c = num.toString(8); // 17 var d = num.toString(16); //f
37
Boolean Object two values: true or false. Create a Boolean object: – var myBoolean=new Boolean(value); – Value is optional. If no initial value, or one of the following: – 0 – -0 – null – "" – false – undefined – NaN The Boolean object is set to false.
38
Boolean Object - Methods toString(): – Converts a Boolean value to a string, and returns the result. var bool = new Boolean(1); var myvar = bool.toString(); alert(myvar); output: true
39
Boolean Object - Methods valueOf(): – Returns the primitive value of a Boolean object var bool = new Boolean(null); var myvar = bool.valueOf(); alert(myvar); output: false
40
Regular expressions: patterns used to match character combinations in strings. Regular expressions are objects. To search in a text, use a pattern to describe what you are searching for. Are used to perform powerful pattern-matching and "search-and-replace" functions on text. 40 Regular Expression
41
Syntax: var patt=new RegExp(pattern,modifiers); var patt=/pattern/modifiers; – Pattern: specifies the pattern of an expression – Modifiers: specify if a search should be global (g), case- insensitive (i), etc. E.g., – var patt1=new RegExp(“is”, g); – var patt1=/is/g;
42
42 Regular Expression - Methods RegularExpression.test(string): -Searches a string for a specified value, and returns true or false, depending on the result. var str="Is this all there is?"; var patt=new RegExp("E", "i"); alert("pattern ‘E' is in 'str': " + patt.test(str)); output - pattern ‘E' is in 'str': true var str="Is this all there is?"; var patt=new RegExp("E"); alert("pattern ‘E' is in 'str': " + patt.test(str)); output - pattern ‘E' is in 'str': false
43
43 Regular Expression - Methods RegularExpression.exec(string): searches a string for a specified value, – returns a result array or null. var str="Is this all there is?"; var patt=new RegExp("is", "i"); alert("pattern ‘is' is in 'str': " + patt.exec(str)); output - pattern ‘is' is in 'str': Is
44
44 Regular Expression - Methods String.match(pattern): - returns the matching patterns, - if no matching, return null. - without the modifier “g”, returns same as exec(); var str="Is this all there is?"; var patt=/is/g; alert(str.match(patt)); output - is,is var str="Is this all there is?"; var patt1=/is/gi; alert(str.match(patt1)); output – Is, is,is
45
Regular Expression - Methods String.search(RegularExpression): – search the RegularExpression in the specified string. – Return the index of the first match of the RegularExpression in the string, – Return -1, if no match – E.g., var re = /or/; var s = "Good morning"; alert(s.search(re)); // 6 45
46
Regular Expression – Special Characters *: matches the preceding character 0 or more times, /ab*c/ matches “abbbbc” and “ac”, but not “ad” +: matches the preceding character 1 or more times /ab+c/ matches “abbbc” and “abc”, but not “ac” ?: matches the preceding character 0 or 1 time. /ab?c/ matches “abc” and “ac” ^: Matches beginning of input $: Matches end of input {n}: Matches exactly n occurrences of the preceding character. N must be a positive integer. More on MDN (Mozilla Developer Network): https://developer.mozilla.org/en- US/docs/Web/JavaScript/Guide/Regular_Expressions https://developer.mozilla.org/en- US/docs/Web/JavaScript/Guide/Regular_Expressions 46
47
Regular Expression - Brackets Brackets are used to find a range of characters
48
Example var name = prompt("Enter a name"); var nameRegEx = /^[A-Za-z][0-9 A-Za-z \'\-]*$/; if(nameRegEx.test(name)==true) alert("Yes"); else alert("No"); 48
49
Example var phone = prompt("Enter Phone:"); var phoneRegExp = /^\([0-9]{3}\)[0-9]{3}\-[0-9]{4}$/; if(phoneRegExp.test(phone)==true) {alert("Yes");} else alert("No"); 49
50
Next Class HTML 50
51
Thank you!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.