1 / 72

BIT116: Scripting Lecture 10

BIT116: Scripting Lecture 10. Instructor: Craig Duckett cduckett@cascadia.edu. Monday, February 10 th , 2014. Debugging, String Object, Regular Expressions. A Word About the Mid-Term. The Mid-Term is this Wednesday, February 12 th

zurina
Télécharger la présentation

BIT116: Scripting Lecture 10

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. BIT116: ScriptingLecture 10 Instructor: Craig Duckett cduckett@cascadia.edu Monday, February 10th, 2014 Debugging, String Object, Regular Expressions

  2. A Word About the Mid-Term The Mid-Term is thisWednesday, February 12th This one-time-only it will be open notes, and open book, but no Internet. Let me repeat: NO Internet. The Mid-Term is not difficult, but will be used primarily as a way for me to access whether you are understanding and retaining some of the basic principles of JavaScript. Most of you won't even need to use your notes or the book. The Final Exam will be similar, and I'm debating whether to make it closed notes and closed book. Why? Because it will not be difficult! What I ultimately feel is important for the successful completion of this class are the Four Assignments, and so I have not made the Mid-Term or the Final Exam particularly hard. In fact, I'm guessing the Mid-Term may be own of the easier Mid-Terms you will have taken here at Cascadia.

  3. A Word About the Mid-Term CONTINUED • The Mid-Term will consist of the following: • (6) True/False Questions [30 points] • (10) Multiple Choice Questions [50 points] • (6) Explain the Error Questions [30 points] • (1) Writing Code [20 points] (you are asked to write a function which will contain an Array, then prompt the user to fill it; then the code will sort it, and write the results to the page) • (1) Find the Errors [20 points] (you are asked to find up to 10 errors, briefly show how to fix them) • The entire class time is dedicated to the Mid-Term. Most should finish it in under an hour. Some will finish a lot sooner, some others may need more time. • When you are finished with the Mid-Term, hand it in quietly and you are done for the day  • Remember, the college is closed on Monday, February 17th(President's Day), so have a nice long weekend! • Also remember, Assignment 2 is due Monday, February 17th, uploaded to StudentTracker by midnight.

  4. Debugging

  5. Testing and Debugging Testing – When you test an application you run it to make sure it works correctly. You try every possible combination of input data and user actions to be certain that the application works in every case. In other words, the goal of testing is to make the application fail. Debugging – When you debug an application, you fix the errors (called "bugs") that you discover during testing. Each time you fix a bug, you test again to make sure that the change you made didn't affect any other aspect of the application

  6. Typical Test Phases for a JavaScript Application When you test an application, you typically do so in phases. In the first phase, as you test the user interface, you should visually check the controls to make sure they’re displayed properly with the correct text. Then, you should make sure that all the keys and controls work correctly. In the second phase, you should test the application with valid data. To start, you can enter data that you would expect a user to enter. Before you’re done, though, you should enter valid data that tests all of the limits of the application. In the third phase, you go all out to make the application fail by testing every combination of invalid data and user action that you can think of. That should include random actions like pressing the Enter key or clicking the mouse at the wrong time.

  7. Three Types of Errors That Can Occur As you test an application, there are three types of errors that can occur: Syntax Errors- Because syntax errors prevent your application from running, they are the easiest to find and fix. As you will see, a typical web browser provides error messages that help you do that. Runtime Errors- Although runtime errors don’t violate the syntax rules, they do throw exceptions that stop the execution of an application. Unlike other languages, though, JavaScript doesn’t throw many of the traditional exceptions. For instance, if you divide a number by zero, JavaScript returns “infinity” instead of throwing an exception. Logical Errors- Logic errors can come from many places, and they are often the most difficult to find and correct. A mistake in a calculation, events not being triggered in the order you expect them to, and working with incorrect values are just a few of the ways that logic errors can creep into your applications.

  8. Using Browser to Detect Errors

  9. Firefox: The Error Console The Firefox Error Console as described in the Murach's book has been deprecated. However, it can still be enabled through Firefox's 'secret' configuration window. Here's what you need to do: In Firefox's address bar, type in: devtools.errorconsole.enabledThis will bring up this scary warning screen: Click the I'll be carefull, I promise! button. Search to devtools.errorconsole.enabled and double-click on it to change its value to true You might also want to change the value of devtools.errorconsole.deprecation_warnings to false.

  10. Firefox To use the Error Console in Firefox, go to the web page that you want to check, then from the menu bar select Tools > Web Developer > Error Console Select the Errors tab to narrow the messages down to a dull roar: Double-click on the "link" in the Error Console that shows the code to open the file. The use of the Error Console doesn't fix the error for you, it just shows you where it is. It's up to you to go into your editor to fix the code, then test it again.

  11. Firefox: The Web Console The Firefox Error Console has been deprecated and replaced by the Web Console, with a much slicker and useful interface. Surf to the page you want to check, then from the menu bar select Tools > Web Developer > Web Console Select the JS tab, then check Errors You can access where the errors occur in the code by clicking on the blue links on the right-hand side of the errors

  12. Firefox: The Debugger In addition to the Firefox Web Console there is the JavaScript Debugger. See video https://developer.mozilla.org/en-US/docs/Tools/Debugger Surf to the page you want to check, then from the menu bar select Tools > Web Developer > Debugger

  13. Firefox: Firebug In addition to the Firefox Debugger there is the Firebug add-on: http://getfirebug.com/ Quick Tour of Firebug: https://getfirebug.com/screencast.html Also: http://www.softdevtube.com/2010/05/10/using-firebug-to-debug-javascript/

  14. String Objects

  15. Introduction to the String Object • The String object provides properties and methods to get information about strings or to modify strings. • A String object is created in either of two ways: • a programmer creates one by using the new keyword with the constructorfunction • JavaScript creates one temporarily when one of the methods is called from a string literal. • What makes a String object and what makes a string literal? • To find out, we'll take a look at how to create a String object in JavaScript.

  16. The String Object • As just explained, one way to create a String object is to use the new keyword, as you’ve done with other objects previously. The syntax is shown here: • varinstanceName= new String("string value here"); • You replace instanceNamewith the name you want to use for the instance of the String object. You then replace string value here with the string of characters to use as the new String object. • So, if you want to create an instance of the String object named guitarString, you could use the following code: • varguitarString= new String("G"); • This script creates an instance of the String object for the string “G”. • Although creating a String object with the new keyword can be useful for things such as comparing String objects, string literals are used more often.

  17. The String Literal • You can create a string literal just by assigning a string value to a variable. • This technique is a bit shorter than creating a String object using the new keyword and still allows you to use all the methods of the String object (as well as one of the properties). • A string literal is created in the code that follows. Notice that the code assigns a string value to a variable. • varguitarString= "G"; • This makes the string “G” a string literal, which you know as a regular text string. • With text strings, you’re also allowed to use the properties and methods of the String object.

  18. What's the Difference Between a String Object and a String Literal? • The difference between a String object and a string literal is that a regular text string has the value of the string itself, and it can be compared against another string easily, as in the following code: • varguitarString1 = "E"; • varguitarString2 = "E"; • if (guitarString1 == guitarString2) { • window.alert("The strings are the same!"); • } • else { • window.alert("The strings are not the same!"); • } • Because this code uses regular string literals, the result is what you’d expect. An alert says that the strings are the same.

  19. What's the Difference Between a String Object and a String Literal? • However, if you used String objects to run through the same if block, you would see something unexpected. The code that follows uses String objects instead: • var guitarString1 = new String("E"); • varguitarString2 = new String("E"); • if (guitarString1 == guitarString2) { • window.alert("The strings are the same!"); • } • else { • window.alert("The strings are not the same!"); • } • This time the alert would tell you that the strings are not the same, even though the string values are both “E” because a String object is an object value and not a literal value. Objects aren’t going to be equal to one another in the same way regular text strings would be. Why? Because what's being compared are the addresses of the String objects and not the string itself! • So, you would probably use string literals and let them use the String object’s methods.

  20. What's the Difference Between a String Object and a String Literal? A regular text string is able to use the String object’s methods because JavaScript takes the string literal and turns it into a temporary String object. Once the method’s execution is complete, it returns a string literal. This allows you to use the String object’s methodswithout having to create String objects.

  21. Using the Properties of the String Object

  22. Using String Object Properties The String object has only three properties, so this section is relatively short. The table below provides a brief description of these properties, each of which is discussed in turn in the slides that follow.

  23. Using String Object Properties • The constructorProperty • This property sends back the syntactic value of the constructor function. To use the constructor property, you have to use a String object rather than a literal. • The following code writes the value of the constructor property onto a web page: • <body> • <script> • var test = new String("Testing the Constructor is such a gas!"); • document.write(test.constructor); • </script> • </body> • This code produces text similar to the following in the browser (not that helpful, but here it is): • function String() { [native code] } http://faculty.cascadia.edu/cduckett/bit116/Lecture_10/string_constructor.html

  24. Using String Object Properties • The length Property • The lengthproperty returns the length of the string, which is the number of characters contained in the string. You can use it with both String objects and string literals. You’ve seen this property with other objects as well, such as the Array object. (In that case, the value was the number of elementsin an array.) • The following code uses a regular text string. It writes the length of the string variable onto the page. • <body> • <script> • varmyname="Winkus"; • document.write("The name has " + myname.length + " characters."); • </script> • </body> • Notice how the name of the variable is used like an object name here. This is how to get JavaScript to create a temporary String object to use the property. The script writes the result to the page. Because the name has six characters, the length property has a value of 6 here. The length property will be quite useful when you want to break strings apart to get information or make changes.

  25. Using String Object Properties • The prototype Property • As with the other objects that have the prototype property, you can use it to add properties or methods to String objects on the page. • The following code shows an example: • String.prototype.attitude = "cool"; • varrightNow = new String("Rex"); • window.alert("This string is " + rightNow.attitude); • Now the String object “Rex” has an attitude property of “cool”

  26. Using the Methods of the String Object

  27. Using String Object Methods

  28. Using String Object Methods CONTINUED The String object has a lot of methods, as shown in table in the previous slide. Yes, this list is quite long! The following slides will take a quick look at some of the more common (or most used) methods of the String object.

  29. String Methods That Add HTML Tags CONTINUED • The basic methods big(), blink(), bold(), fixed(), italics(), small(), strike(), sub(), and sup() simply add the basic HTML tags around the string. • For example, to create some small text, you could use the small() method: • varsingleSlice= "I only want a single slice of sausage pizza."; • vardinky = singleSlice.small(); • document.write(dinky); • This code would then write the following into the HTML code: • <small>I only want a single slice of sausage pizza.<small> • When viewed in the browser, this text would appear smaller than it would normallyhave appeared without the <small> and </small> tags. http://faculty.cascadia.edu/cduckett/bit116/Lecture_10/string_methods.html

  30. String Methods That Add HTML Tags CONTINUED The remaining HTML tag methods anchor(), fontcolor(), fontsize(), and link() take in parameters and build the tags based on the string value and the parameter(s) sent to them. These will be discussed a bit more in the following slides.

  31. String Methods That Add HTML Tags • The anchor() method • This method places a text string as the text for a named anchor. The anchor() method takes a parameter that will be the name attribute for the named anchor. • Basically, it creates an HTML tag set with the following syntax: • <a name="parameterString">textString</a> • The parameterStringis a string you send as a parameter in the method call. The textString is the value of the string from which you call the method.

  32. String Methods That Add HTML Tags • The anchor() method CONTINUED • For example, take a look at this code: • varanchorText= "Some Groovy Text a the Top of the Page"; • varfullAnchor= anchorText.anchor("top"); • document.write(fullAnchor); • Here, you assign a string literal to the variable anchorText. You then call the anchor() method with a parameter of “top” from the string literal. The result is assigned to the fullAnchorvariable. • The value of the fullAnchorvariable is then written on the page. The code writes the following link into the code for the page: • <a name="top">Go to Top</a> • And this is what's displayed in the browser: • Go to Top

  33. String Methods That Add HTML Tags • The fontcolor() method • The fontcolor() method adds font color to the text string that is used to call it. It takes in a • string parameter that indicates what color the text should be. The color can be sent using either • the color "name", #hex, or (RGB) value. • <body> • <script> • vartheText= "I am so mad I see red!"; • document.write(theText.fontcolor("red")); • </script> • </body> • This is what is displayed in the browser: • I am so mad I see red! http://www.w3schools.com/jsref/jsref_fontcolor.asp

  34. String Methods That Add HTML Tags • The fontsize() method • The fontsize() method adjusts the font size of the text string that calls the method. It takes in a numeric value to represent the size of the text (between 1 and 7). • <body> • <script> • vartheText= "I am pretty small!"; • document.write(theText.fontsize(2)); • </script> • </body> • This is what is displayed in the browser: • I am pretty small! http://www.w3schools.com/jsref/jsref_fontsize.asp

  35. String Methods That Add HTML Tags • The link() method • NOTE: The link() method is not standard, and may not work as expected in all browsers. • The link() method is used to display a string as a hyperlink. This method returns the string embedded in the <a> tag, like this: • varsomeString= "Programajama or Bust! • var result = someString.link("http://www.programajama.com"); • document.getElementById("demo").innerHTML = result; • <p id="demo"></p> • This is what is displayed in the browser: Programajama or Bust! http://faculty.cascadia.edu/cduckett/bit116/Lecture_10/link_method_1.html http://faculty.cascadia.edu/cduckett/bit116/Lecture_10/link_method_2.html http://www.w3schools.com/jsref/jsref_link.asp

  36. String Methods That Add HTML Tags • The charAt() method • The charAt() method determines which character resides at a particular position in a string. You can find out what the first or last character is, or you can find any character in between. The charAt() method takes in a number representing the position where you want to know the character. • The index of the first character is 0, the second character is 1, and so on. The index of the last character in a string is string.length-1, the second last character is string.length-2, and so on. • varstr = "HELLO WORLD";var res = str.charAt(0) • Result would be: H • varstr = "HELLO WORLD";var res = str.charAt(str.length - 1); • Result would be: D http://www.w3schools.com/jsref/jsref_charat.asp

  37. String Methods That Add HTML Tags • The charCodeAt() method • The charCodeAt() method works the same way as the charAt() method, but it returns the character ASCII code for the character at the positions sent as the parameter. • The character ASCII code is a numeric code that can be substituted for characters in HTML. In HTML, you can write an angle bracket (<) to show code on a Web page—without the angle bracket converting to HTML itself—by using a special character code. In place of a regular angle bracket, for example, you could use &#60. The charCodeAt() method returns the numeric part of that code, the 60. • The charCodeAt() method can be useful if you want to find out the character code for a certain character. • varstr = "HELLO WORLD";var n = str.charCodeAt(0); • The result world be: 72 http://www.w3schools.com/jsref/jsref_charcodeat.asp

  38. String Methods That Add HTML Tags • The concat() method • This method works much like the Array object’s concat() method. It combines the text string that calls the method with any number of other text strings sent as parameters and returns the combined value. The text string calling the method comes first in the order, while the strings sent as parameters are added in order after it. • var string1 = "I went to the store "; • var string2 = "then "; • var string3 = "I played a video game"; • window.alert(string1.concat(string2,string3)); http://www.w3schools.com/jsref/jsref_concat_string.asp

  39. String Methods That Add HTML Tags • The fromCharCode() method • The fromCharCode() method creates a string from a series of character ASCII codessent as parameters to the method. The charCodeAt() method returns a numeric code for the character at a given position. This is the type of value you must send to the fromCharCode() method. • Also, fromCharCode() is called directly from the String object rather than from an existing string, because it is piecing together a string on-the-fly and doesn’t require one to run. Instead, it uses the parameters sent to it to return a string. • var res = String.fromCharCode(72,69,76,76,79); • The result would be: HELLO http://www.w3schools.com/jsref/jsref_fromcharcode.asp

  40. String Methods That Add HTML Tags • The indexOf() method • The indexOf() method returns the position of the first occurrence of a specified value in a string. • This method returns -1 if the value to search for never occurs. • Note: The indexOf() method is case sensitive. • Tip: Also look at the lastIndexOf() method on the next slide. • varstr = "Hello world, welcome to the bizarre universe!";var n = str.indexOf("welcome"); • The result would be: 13(i.e., the 'w' in welcome is at the 13th position in the string starting at 0) http://www.w3schools.com/jsref/jsref_indexof.asp

  41. String Methods That Add HTML Tags • The lastIndexOf() method • The lastIndexOf() method finds out where the last instance of a certain character or string is located in the string. It returns the position of only the last occurrence of the character or string that is sent as the parameter. If the character or string isn’t found in the string value, a value of –1 is returned. • . • Note: The lastIndexOf() method is case sensitive! • varstr = "Hello planet earth, you are a goofy planet.";varres = str.lastIndexOf("planet"); • The result would be: 36(i.e., the 'p' in the second 'planet' is at the 36th position in the string starting at 0) http://www.w3schools.com/jsref/jsref_lastindexof.asp

  42. String Methods That Add HTML Tags • The slice() method • This method pulls out a portion of a string and returns a new string, which is the text string that was sliced. The slice() method takes in two numeric parameters to tell it where to beginand endthe portion of the string to be pulled. This method works much like the slice() method of an array. The first parameter tells it the position at which to start slicing, while the second parameter is one greater than the position where it will stop. For instance, take a look at the code that follows (and, yes, this still confuses me so I always have to look it up!): • vartheText= "Do not cut this short!"; • varshorterString= theText.slice(0,7); • window.alert(shorterString); • This code slices the string from position 0 through position 6. Position 7 is where the c is in “cut”; but it is notsliced because the parameter to end is not included as a position to slice, but is one greater! (see why I still get confused—it's all about 0 through 6, not 1 through 7!) • The alert will say “Do not ” (including the space after the 't' in 'not') http://www.w3schools.com/jsref/jsref_slice_string.asp

  43. String Methods That Add HTML Tags • The split() method • The split() method creates an array of string elements based on the string it splits. The string is split based on a character sent as a parameter that acts as a separator. • For instance, the code that follows has a string with a bunch of colons in it: • vartheText= "orange-apple-pear-grape"; • varsplitText= theText.split("-"); • varendCount= splitText.length; • for (varcount = 0; count < endCount; count++) { • document.write(splitText[count] + "<br>"); • } • The string assigned to the theTextvariable has a bunch of fruits separated by dashes (-). The next line creates an array named splitTextby using the split() method on the text string theText. The parameter sent is a dash, which is what is used to separate the string into array elements. In this case, the array ends up with four unique elements. http://www.w3schools.com/jsref/jsref_split.asp

  44. String Methods That Add HTML Tags • The substr() method • The substr() method pulls out a portion of a string and returns the portion that is removed as a new string. It takes two numeric parameters. The first parameter specifies the beginning of the removal, and the second parameter specifies how many characters to remove. • For instance, the following code removes a portion of a string beginning at position 0and continues until seven characters are removed: • vartheText= "Don't taze me, bro!"; • varshorterString= theText.substr(0,7); • window.alert(shorterString); • This code removes everything up to the beginning of the word 'taze' in the string. The string returned is the portion of the string that has been removed. Thus, the alert will say “Don't t”. http://www.w3schools.com/jsref/jsref_substr.asp

  45. String Methods That Add HTML Tags • The substring() method • This method works much like the substr() method, but it allows you to send parameters for the beginning position and the ending position of the portion of the string you want to remove. It then returns the removed portion as a new string. • For example, take a look at the code below. Rather than specifying the number of characters to remove, you give an ending position. The characters are removed beginning at the starting position and ending at one less than the ending position. [And yes, this still confuses me to this day…I always have to look it up!] • vartheText= "Do not cut this short!"; • varshorterString= theText.substring(3,7); • window.alert(shorterString); • You remove everything between the beginning of the string and the beginning of the word “cut”. • The alert will say “not ” (including the space after the 't' in 'not') http://www.w3schools.com/jsref/jsref_substring.asp

  46. String Methods That Add HTML Tags • The toString() method • The toString() method returns a string literal value for a String object that calls it. Here’s an example of how you can use this method: • varstringObject= new String("Cool"); • varstringLiteral= stringObject.toString(); • This code takes the String object and uses the toString() method to get its string literal value. It then assigns that value to the stringLiteralvariable. http://www.w3schools.com/jsref/jsref_tostring_string.asp

  47. String Methods That Add HTML Tags • The toLowerCase() method • This method returns in lowercase letters the value of the string that called it. Take a look at this code: • <body> • <script> • vartheText= "I FEEL CALM, REALLY."; • document.write(theText.toLowerCase()); • </script> • </body> • This code writes the string in all lowercase letters on the page, like this sample text: • ifeel calm, really. • Note: The toLowerCase() method does not change the original string. http://www.w3schools.com/jsref/jsref_tolowercase.asp

  48. String Methods That Add HTML Tags The toUpperCase() method This method returns in uppercase letters the value of the string that called it. Here’s an example: <body> <script> vartheText= "I am yelling!"; document.write(theText.toUpperCase()); </script> </body> This code writes the string in all uppercase letters on the page, like this sample text: I AM YELLING! Note: The toUpperCase() method does not change the original string. http://www.w3schools.com/jsref/jsref_touppercase.asp

  49. Regular Expressions

More Related