· 8 years ago · Jan 31, 2018, 03:52 PM
1Lesson 6--- COPY CODE INTO DREAMWEAVER:
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
7<title>Lesson 6: Language Objects</title>
8<link href="styles4.css" rel="stylesheet" type="text/css" />
9<script type="text/javascript">
10
11//lab 6-1
12
13function lab61() {
14
15 alert("Lab 6-1 Steps:\n Step 1: Copy the code for the function linksFun() on page 6-7\n Step 2: Identify where the instructions in the comments appear in the code\n Step 3: Add the href code from page 6-8 in the body with the image as the CIW logo\n Step 4: Test your new code\n Step 5: Examine the javascript:void mechanism explanation proceeding the lab on page 6-9");
16
17}
18
19
20function linksFun() {
21 var content="", linkWindow;
22 //Add the alert () shown in figure 6-1
23 alert("The following page provides links to: \n\nCIW\nCIW Candidate Log-In \nComputerPREP");
24
25 content += "<html><head><base target='_blank'></head><body>";
26 content += "";
27
28 //Add big() and fontcolor() methods
29 content += "CIW Sites".big().fontcolor("blue");
30 content += "<p>\nThese are sites of interest to ";
31
32 //Add italics() method
33 content += "CIW".italics();
34 content += " candidates.</p>\n";
35 content += "<ul><li>";
36
37 //Add link() method
38 //Use http://www.CIWcertified.com
39 content += "CIW".link("http://www.CIWcertified.com");
40 content += "\n</li>";
41
42 content += "\n<li>";
43 //Add link() method
44 //Use http://www.CIWcertified.com/CandidateLogin
45 content += "CIW Candidate Log-In".link("http://CIWcertified.com/CandidateLogin");
46 content += "\n</li>";
47 content += "\n<li>";
48 //Add link() method
49 //Use http://www.ComputerPREP.com/
50 content += "ComputerPREP".link("http://www.ComputerPREP.com/");
51 content += "\n</li></ul></body></html>";
52
53 linkWindow=open("","Links","width=350,height=200,resizable=1");
54
55 with(linkWindow.document) {
56 open();
57 write(content);
58 close();
59 }
60
61}
62
63
64//blueverdana font
65
66function blueVerdanaFont() {
67
68 return "<span style='font-face:Verdana;color:blue;font-size:2em'>" +
69 this.toString() + "</span>";
70}
71String.prototype.blueV = blueVerdanaFont;
72String.prototype.blueVDescription = "The blueV() function creates blue Verdana font.";
73
74
75function blueVerdanaFontTwo() {
76 document.write("The following text is " +
77 "blue Verdana".blueV() + " font.");
78 document.write("<p>" + "blueV".blueVDescription + "</p>");
79 document.write("<strong>Take note that this function blueVerdanaFontTwo() is based on the function blueVerdanaFont()</strong>");
80
81}
82
83
84function practiceOne() {
85 document.write("\"My name is zack!\".length; <br>");
86}
87
88
89function sampleCode() {
90 var myEmail = "gregory@someplace.com";
91var start = myEmail.indexOf("@") + 1;
92var myHost = myEmail.substring(start, myEmail.length);
93alert(myHost + " ---> This is the host name in the email adress");
94
95
96}
97</script>
98
99
100
101
102
103</head>
104
105<body>
106
107<h1>Lesson 6: Javascript Language Objects</h1>
108
109<h3><em><strong><a href="#string">String object</a>, <a href="#evaluatestrings">Evaluating strings</a>, Basic Expressions & RegExp, Array Object, Date & Math, End of Lesson Labs</strong></em></h3>
110
111<hr />
112
113<h3>Lesson Overview</h3>
114<p>In Javascript X/HTML forms and form elements are objects that can be used to manipulate string, date and math information in useful ways.<br />
115 For example, you can use the String object to manipulate and test the values in form elements before they are sent to GCI scripts and other processes.</p>
116<p>The <em>String, Math, Array, Date and RegExp</em> objects are called language objects. They are not part of the containment hierarchy shown in the previous lesson, but are nevertheless part of the Javascript language.</p>
117
118<hr />
119
120<div id="string">
121<h3>The String Object</h3>
122<p>A string can be text, numbers, or any combination of characters that functions as text such as, "How are you today?" or in the values of variables, such as userName. You have already seen one method of the string object. the toUpperCase() method.<br />
123Any existing string in your scripts can access the methods of the JavaScript String object. JavaScript offers the "new String()" constructur, which creates instances of a String Object. For example:</p>
124<p>var myStringObject = new String("This is a string object.");<br />
125myStringObject = myStringObject.toUpperCase()</p>
126<p>You do not always have to create a formal String object to use String object properties such as the following example</p>
127<p>var myString = "This is a string.";<br />
128myString = myString.toUpperCase();</p>
129<p>The <em>String</em> object has methods that allow you to:</p>
130<ul>
131<li>Test for the presence of certain characters.</li>
132<li>Extract a subset (called a substring) form a given string.</li>
133<li>Find the position of a given character or substring in a string</li>
134<li>Retrieve the number of characters in a string</li>
135</ul>
136
137<h4><em>String</em> object formatting methods</h4>
138<p>The string object provides predefined methods for formatting text, which are useful when applying string display characteristics to JavaScript-generated X/HTML. For example, you can make a text string appear in bold by:</p>
139<p>docment.write("Hello, World!".bold());<br />
140document.write(userName.bold());</p>
141<p>The first example demonstrates how the String object can reduce the amount of typing in some situtations instead of typing code such as: document.write("|b|Hellow, World!|/b|");</p>
142
143<p><b>NOTE: VIEW TABLE 6-1 FOR FORMATTING METHODS OF THE STRING OBJECT</b></p>
144
145<p>Note that String object formatting methods can be added to the same string at once:</p>
146<p>document.write("Warning".fontsize(7).anchor('warningText'));</p>
147
148<h4><em>String</em> object special characters</h4>
149<p>In addition to the special formatting methods , JavaScript provides a set of special characters that you can use to format text or simulate certain keystrokes. <b>VIEW TABLE 6-2 FOR THESE SPECIAL CHARACTERS</b></p>
150
151<p>Do not confuse the new special characters with other symbols in a script such as "\\" (which would display as stated).<br /></p>
152<p>If you wanted to put quotations around the word favorite in: document.write("favorite".italics()); you would do:<br />
153document.write("\"favorite\"".italics());</p>
154
155<hr />
156
157<h3><em>Lab 6-1</em></h3>
158
159<form>
160<input type="button" value="Lab 6-1 Instructions" onclick="lab61()" />
161</form>
162<br />
163<p><strong>Clicking on the CIW Logo will activate Lab 6-1</strong></p><br />
164
165
166<a href ="javascript:void(linksFun());" onmouseover="status='CIW Links';return true;" onmouseout="status='';return true">
167<img src="../images/ciw_logo.jpg" width="181" height="84" border="0" /></a>
168
169<hr />
170
171<h3>The String Object (contd.)</h3>
172
173<h4>The prototype property of the String Object</h4>
174<p>The String object provides the powerful prototype property. This allows you to create your own methods and properties for the String object.<br />
175 After you create new methods/properties for the String object w/
176 the prototype property, they are available to any subsequent String objects in the current document.</p>
177
178
179
180<form>
181<input type="button" value="Try the prototype property" onclick="blueVerdanaFontTwo()" />
182</form>
183
184<h4>Common Syntax Errors with the String object</h4>
185
186<p>Review the textbook on page 6-11 on a common syntax error. Note for multiple methods to be applied at the same time they must be stacked such as:<br />
187<br />
188var myString = "This is text";<br />
189
190document.write(myString.toUpperCase().bold());</p>
191
192</div>
193
194<hr />
195
196<div id="evaluatestrings">
197
198<h3>Evaluating Strings</h3>
199
200<p>This section will teach you to effectively examine your string data for programming purposes</p>
201
202<h4>The length property of the String object</h4>
203
204<p>A common task in data validation is to test the length of a string. For example, suppose you create a form with a text box in which the user enters his or her e-mail address.<br />
205 Before the form is submitted, you can test whether the e-mail address has at least siz characters. To determine the length of any string, you can use the length property. This syntax is:<br />
206<br />
207string.length;<br />
208<br />
209"Hello, World!".length;<br />
210<br />
211The expression would result in the integer value of 13, or the number of characters including the blank space. Here's an example that tests the length of a variable:<br /><br />
212
213var userName = "Jose";<br />
214userName.length;<br />
215The statement would result in the integer value of 4.</p>
216
217<h4>The indexOf() method of the String object</h4>
218
219<p>The indexOf() method tests for the presence of a given character and returns an index value representing the caracter's position in the string. The generic syntax of the indexOf() method is as follows:<br />
220<br />
221string.indexOf(searchText, startingIndexPosition);<br />
222<br />
223Consider the following statement:<br />
224<br />
225"This is a test".indexOf("h", 0);<br />
226<br />
227The argument ("h", 0); instructs the indexOf() method to search the string for the first occurrence of the letter h starting at the character indexed zero (first character in the string).<br />
228 This statement would return the value 1 because the letter h is the first character to the right of the beginning of the string. In JavaScript, the index for the string is zero-based. Thus, the letter T in the example is in position 0.</p>
229
230 <p><mark>NOTE</mark>: A value of -1 always indicates the sought-after string was not found, searching forward from the specified starting position, and if a startingIndexPosition is not specified , the search will always begin at the first character (position 0) in the String</p>
231 <hr />
232 <h4>Practice</h4>
233
234 <p>Use the length property of the string object to determine the number of characters in the phrase "My name is zack!"</p>
235 <form>
236 <input type="button" value="Solution" onclick="practiceOne()" />
237 </form>
238
239<hr />
240
241<h4>The lastIndexOf() method of the string object</h4>
242<p>This method returns the index value for the starting position of the last occurrence of the search text specified. It searches from the ending position instead of the starting position of the string. The generic syntax for lastIndexOf() is as follows:<br />
243string.lastIndexOf(searchText, startingIndexPosition);<br /><br />
244
245For example:<br />
246
247"ABRACADABRA".lastIndexOf("ABRA", 10);<br />
248instructs the lastIndexOf() method to search for the last occurrence of ABRA starting at the tenth, or last, character of the string. This would return a value of 7, even though ABRA occurs first starting at position 0.</p>
249<p>Similar to the indexOf() method the lastIndexOf() method will start at the end of the string if no startingIndexPosition is specified</p>
250
251<h4>The substring() method of the String object</h4>
252<p>When you want to examine and extract a portion of a string, you can use the substring() method. The generic syntax is as follows:<br />
253string.substring(startingIndexPosition, endingIndexPosition);<br /><br />
254
255For example:<br />
256"ABC1234XYZ".substring(3,7);<br />
257would return "1234"</p>
258<p><mark>NOTE:</mark> The endingIndexPosition is NON INCLUSIVE, therefore "X" would not be included in the return</p>
259
260<p>The substring() and indexOf() methods are often used in tandem to preform string manipulation and validation. For instance:<br />
261<br />
262var myEmail = "gregory@someplace.com";<br />
263var start = myEmail.indexOf("@") + 1;<br />
264var myHost = myEmail.substring(start, myEmail.length);<br />
265alert(myHost);<br />
266
267<p>Try the code above</p>
268<form>
269<input type="button" value="Sample Code" onclick="sampleCode()" />
270</form>
271
272<h4>The substr() method</h4>
273<p>This method is used to extract a portion of a string, as the substring() method does. However the arguments for these two methods differ;</p>
274<ul>
275<li>substr() - You specify the beginning index position and the number of characters to the exact starting at that position</li><br />
276
277 <li>Ex: var myString = "This is text.";<br />
278 var mySubStr = myString.substr(1, 3);</li>
279 alert(mySubStr);<br />
280
281 -- would return a value of "his"<br /><br />
282
283
284<li>substring() - You specify the beginning index position and the ending index position<br /><br />
285
286Ex: var myStrubg = "This is text.";<br />
287 var mySubString = myString.substring(1, 3);<br />
288 alert(mySubString);<br />
289 -- would return a value of "hi"
290
291</li>
292</ul>
293
294<h4>The charAt() method of the String object</h4>
295<p>When you want to extract a single character that occurs at a specific string, you can use the charAt() method. The generic syntax goes as follows:<br />
296<br />
297string.charAt(indexPosition);<br />
298<br />
299The indexPosition argument is an integer value that represents the index position the character to be extracted. For example,<br /><br />
300
301"ABCDEF".charAt(3); would return the value D</p>
302
303<b><mark>Question</mark></b>: What value would the variable "char" hold after the following code?
304
305<p>var myString = "ABCXYZ";<br />
306var char = myString.charAt(myString.length - 1);</p>
307
308<form>
309<input type="button" value="Solution" onclick="charAtSolution()" />
310</form>
311
312<script>
313function charAtSolution() {
314 alert("Z, the variable char will take the string length of the varaible myString (6), subtract one (5), and take the 5th character in the string starting from zero");
315}
316</script>
317
318<h4>Form validation using string methods</h4>
319<p>Read the text on page 6-15 about the different uses for string methods for form validation and checking a user's input</p>
320
321<hr />
322
323<h3>Lab 6-2</h3>
324
325<script>
326
327 function showUpper(checked) {
328 var showThis;
329 if (checked) {
330 showThis = document.myForm.name.value.toUpperCase();
331 } else {
332 showThis = document.myForm.name.value.toLowerCase();
333 }
334 document.myForm.name.value = showThis;
335 }
336
337 function emailTest(form) {
338 if (form.email_address.value.indexOf("@", 0) < 0) {
339 alert("This is not a valid email address!");
340 } else {
341 alert("This could be a valid email address");
342 }
343 }
344
345 function showFirst2(form) {
346 var first2Chars;
347 first2Chars = form.phone_number.value.substring(0, 2);
348 alert(first2Chars);
349 }
350
351 function faxNumber () {
352 var strLength = document.myForm.fax_number.value.length;
353
354 alert("The fax number is " + strLength + " characters long");
355 }
356
357
358
359</script>
360
361<form name="myForm" id="myForm">Name:<br />
362
363<input type="text" size="30" name="name" />
364<input type="checkbox" name"upperCheckbox"
365onclick="showUpper(this.checked);"/>
366Convert string to upper case or lower case<br />
367
368E-mail address:<br />
369
370<input type="text" size="30" name="email_address" />
371<input type="checkbox" onclick="(this.checked) ? emailTest(this.form) : '';"/>
372Test for e-mail address<br />
373
374Phone number:<br />
375<input type="text" size="30" name="phone_number" /><br />
376Fax number:<br />
377<input type="text" size="30" name="fax_number" />
378<p>
379<input type="button" value=
380"First Two Characters of Phone Number" onclick="showFirst2(this.form);" />
381</p>
382<p>
383<input type="button" value="Fax Number Length" onclick="faxNumber()" />
384</p>
385</form>
386
387
388<p><mark><strong>Examine Lab 6-2</strong></mark> by reading the text on 6-18 & 6-19 on the functions and form techniques used in Lab 6-2</p>
389
390<hr />
391
392</div>
393
394<div id="regularexp">
395
396<h2>JavaScript Regular Expressions</h2>
397<p>Regular expressions provide a mechanism whereby developers can search for specified patterns in text. They use a string of characters and/or symbols to indentify a pattern in text.<br />
398 The defined pattern is then used to search another string to determine if the pattern exists within that string</p>
399
400 <p><mark>NOTE:</mark> Notice how the RegExp object will be used with regular expressions</p>
401
402 <h4>Creating Regular Expressions</h4>
403
404 <p>The following examples demonstrate the creation of two simple regular expressions:</p>
405 <p>var myRegExp = /Juan/;</p>
406 <p>var myRegExp = new RegExp("Juan");</p>
407 <p>Note that both methods of creating a regular expression are acceptable however the first example is shorter and ultimately more efficient</p>
408
409 <p>After a pattern has been created, it can be used to preform various string operations. For example the RegExp object provides the test() method used to test a string for a matching pattern</p>
410 <p>var myNames = "Paul, George, Ringo, John";<br />
411var myRegExp = /John/;<br />
412document.write(myRegExp.test(myNames));</p>
413<p>The output would be true because the patter /John/ was found in the myNames string.</p>
414
415<h4>More methods of the String object</h4>
416<p>The string object provides several methods that can be used with plain text or regular expressions. These include:</p>
417
418<p><ul>
419<li>test() -- Tests a string for a matching pattern; invoked by a variable representing a regular expression.</li>
420<li>split() -- Splits a string and returns an array of substrings.</li>
421<li>search() -- Searches a string for a string of text and returns the index position of the string, if found.</li>
422<li>match() -- Similar to the search() method, except that it returns an array of matched text instead of an index position</li>
423<li>replace() -- Recieves two arguments: first the string to be replaced, and then the replacement text</li>
424</ul>
425
426<p>The replace() method is demononstrated in the following example</p>
427<p>var myNames = "Paul, George, Ringo, John";<br />
428var myRegExp = /John/;<br />
429myNames = myNames.replace(myRegExp, "Johnny");<br />
430document.write(myNames);</p>
431<p>The output from this example would be Paul, George, Ringo, Johnny. The replace() method recieves two arguments. The first is the string to be replaced, and the second is the replacement text.</p>
432
433<h4>Patterns with alphanumeric characters</h4>
434
435<p>Notice the following example</p>
436<p>var myTelenum = "555-123-1234";<br />
437var myRegExp = /\s{3}-?\d{3}-?\d{4}/;<br />
438document.write(myRegExp.test(myTeleNum));</p>
439<p>The output from this example would be true because the value held by the myTeleNum variable matches the pattern created by myRegExp</p>
440
441<img src="../images/Untitled-1.jpg" width="500" height="250" alt="regular expression from example" />
442
443<p>Read page 6-22 for the breakdown of the previous example</p>
444
445
446<p>Enter your phone number here</p>
447
448<form name="teleForm">
449<input id="phone_num" name="phone" type="text" size="30" />
450</form>
451
452<form>
453<input type="submit" value="Submit Your Phone Number" onclick="testString()" />
454</form>
455
456
457
458<script>
459function testString() {
460
461 var teleNum = document.teleForm.phone.value;
462 var myRegExp = /\d{3}-?\d{3}-?\d{4}/;
463
464 alert("Result of phone number comparison to myRegExp is: " + myRegExp.test(teleNum));
465}
466
467
468
469</script>
470
471
472
473
474 </div>
475<hr />
476<h3>Array Object</h3>
477<p>An array is a single variable with multiple values, which are indexed for easy referencing. In JavaScript, array index are zero-based, meaning the first slot in any array has a default index of 0.</p>
478<p>Some objects you have used already have arrays built in, such as the window object, which has built-in frames that allows you to reference frames by their index number within that array. Form fields can be referenced in a form elements array.</p>
479<p>You can declare any variable to be an array variable using the following syntax:<br />
480<br />
481var questions = new Array();<br />
482or as<br />
483var questions = new Array(10);</p>
484<p>The second example defines an array and pre-designates the maximum number of slots or values it will contain. In this instance 10 elements, but numbers 0-9. Pre-sizing an array provides no real benefit because a value can be assigned to any slot in an array as needed.</p>
485<p>To define individual values in the array, do the following:<br />
486<br />
487var questions = new Array();<br />
488questions[0] = "What is 5*6?";<br />
489questions[1] = "Who played Scarlett O'Hara?";<br />
490questions[2] = "Which horse won the 1980 Irish Derby?";</p>
491<p>If you were to enter [200] for the last line you used a large amount of system memory be creating 201 slots when you only needed 3. questions[2] through [199] would return undefined</p>
492<p>JavaScript provides an alternative syntax when creating an array.</p>
493<p>var answers = new Array(30, "Viven Leigh", "Tyranavos");</p>
494<p>The following syntax could be used to access the answers array elements:<br />
495<br />
496document.write(answers[0]); // outputs 30<br />
497document.write(answers[1]); // outputs Viven Leigh<br />
498document.write(answers[2]); // outputs Tyrnavos</p>
499
500
501
502</body>
503</html>