Bit116 scripting lecture 10
This presentation is the property of its rightful owner.
Sponsored Links
1 / 72

BIT116: Scripting Lecture 10 PowerPoint PPT Presentation


  • 93 Views
  • Uploaded on
  • Presentation posted in: General

BIT116: Scripting Lecture 10. Instructor: Craig Duckett [email protected] 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

Download Presentation

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Bit116 scripting lecture 10

BIT116: ScriptingLecture 10

Instructor: Craig Duckett

[email protected]

Monday, February 10th, 2014

Debugging, String Object, Regular Expressions


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

Debugging


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

Using Browser to Detect Errors


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 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.


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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/


Bit116 scripting lecture 10

String Objects


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

Using the Properties of the String Object


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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”


Bit116 scripting lecture 10

Using the Methods of the String Object


Bit116 scripting lecture 10

Using String Object Methods


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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.


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

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


Bit116 scripting lecture 10

Regular Expressions


Bit116 scripting lecture 10

Using Regular Expressions

Regular expressions give you much more power to handle strings in a script.

They allow you to formpatterns that can be matchedagainst strings, rather than trying to use the String object’s methods, which may make it more difficult to be precise.

For example, you may want to know whether the value entered in a text box for an email address included at least one character at the beginning, followed by an at (@) symbol, followed by at least one character, followed by a dot (.), followed by at least twomore characters (matching a traditional email address like [email protected] the shortest type of email address [email protected]).

The String object’s methods don’t provide a neat and clean way to perform this task (although with enough tinkering, it may be possible).

However, a regular expression can shorten the task or even turn a match that seemed impossible with the String object’s methods into one that can be completed.

http://www.w3schools.com/jsref/jsref_obj_regexp.asp


Bit116 scripting lecture 10

Creating Regular Expressions: RegExpObject

  • To create regular expressions, you must create an instance of the JavaScript RegExp object.

  • You can do this almost the same way as you would create a string literal. To create a RegExpliteral, you just assign the regular expression to a variable.

  • Instead of using quotation marks to surround the expression, you use forward (/) slashes, as shown here:

    • varvarName= /yourPattern/flags;

  • You replace varNamewith the name you want to use for a variable and replace yourPattern with the regular expression pattern of your choice. You can follow the last slash with one or more flags (which are discussed in upcoming slides).

  • NOTE: JavaScript uses forward slashes to let the browser know that a regular expression is between them, the same way quote marks are used to set off strings. Thus, if a forward slash is used within the regular expression, it must be escaped with a backslash in order to work properly. For instance, instead of writing /02/03/2009/, you would need to write /02\/03\/2009/.


Bit116 scripting lecture 10

Creating Regular Expressions CONTINUED

  • The easiest regular expression pattern to create is one that looks for an exact matchof characters.

  • For instance, if you wanted to see if the sequence our is present in a string, you could create the following regular expression pattern:

    • vartoMatch= /our/;

  • The preceding code creates a RegExp literal named toMatch. Now you need a string against which to test the pattern. If you test the word our against the expression, it’s a match.

  • If you test your, sour, pour, or pouring against it, then it’s a match.

  • If you test cool, Our, oUR, OUR, or souR, then it is notbe a match.

  • So how do you perform this test?


Bit116 scripting lecture 10

Testing Strings Against Regular Expressions: the test() method

  • To test a regular expression against a string, you can use the test() method of the RegExp object. The basic syntax is as follows:

    • regexName.test(stringToTest);

  • This syntax is similar to using a string method. You replace regexNamewith the nameof the regular expression and replace stringToTestwith a string or a string variable name.

  • For instance, look at the following example:

    • vartoMatch= /our/;

    • toMatch.test("Kindly pour me another, barkeep!");

  • This code will test the “Kindly pour me another, barkeep!” string against the regular expression named “toMatch.” It doesn’t usethe result, though. So what does it do?

  • The test() method returns a Boolean value of true or false. It returns true when anyportion of the string matches the regular expression pattern.


Bit116 scripting lecture 10

Testing Strings Against Regular Expressions: the test() method CONTINUED

  • Using the test() method, you can already write a short script, as shown here:

    • vartheName= window.prompt("Enter your name","");

    • vartoMatch= /John/;

    • varisMatch= toMatch.test(theName);

    • if (isMatch)

    • {

    • window.alert("Wow, we have the same awesome name!");

    • }

    • else

    • {

    • window.alert("Not my name, but it works for you!");

    • }

  • The prompt gathers a name and holds the value in a variable. The pattern to match is John, and it is case sensitive. Thus, only an entry containing John with a capital J followed by lowercaseo, h, and n will create a match and return true when it is tested (though it could contain more than just John, so entries such as Johnnyor Johnnie or Johnson would also return true—if you want only a specific set of characters, you need to use some additional special characters, which will be discussed a bit later).


Bit116 scripting lecture 10

Testing Strings Against Regular Expressions: Adding Flags

Flags allow you to make the matchcase insensitive or to look for every match in the string rather than just the first one (a global test).

To add a flag, place it after the last slash in the regular expression. You can use three options, as shown in the table below.


Bit116 scripting lecture 10

Testing Strings Against Regular Expressions: Adding Flags CONTINUED

  • If you wanted to adjust the name script used previously to be case insensitive, you could add an i flag to the regular expression, as shown in the following code:

    • vartheName = window.prompt("Enter your name","");

    • vartoMatch = /John/i; // the i flag here makes the r.e. case insensitive

    • varisMatch = toMatch.test(theName);

    • if (isMatch)

    • {

    • window.alert("Wow, we have the same awesome name!");

    • }

    • else

    • {

    • window.alert("Not my name, but it works for you!");

    • }

  • The test() method will now return true as long as the pattern of John is in the string. It can be in any case, so now John, JOHN, john, and even JoHn are all matches and will cause the test() method to return true.


Bit116 scripting lecture 10

Testing Strings Against Regular Expressions: Adding Flags CONTINUED

  • You can also use more than one flag or all three flags at once. For example, if you want to have the match be both case insensitive and global (where it grabs each match in the entire string), you could use the following:

    • vartheName = window.prompt("Enter your name","");

    • vartoMatch = /John/ig; // Two flags, i and g

    • varisMatch = toMatch.test(theName);

    • if (isMatch)

    • {

    • window.alert("Wow, we have the same awesome name!");

    • }

    • else

    • {

    • window.alert("Not my name, but it works for you!");

    • }


Bit116 scripting lecture 10

Creating Powerful Patterns for Regular Expressions

Although it’s nice to be able to create such an exact pattern, you won’t always be looking for a match that is so precise.

In many cases, you will be looking to match a more general pattern, such as an entry that needs to have at least three characters or that needs to have two characters of any type followed by a special character.

By using special characters in your expressions, you can create the type of patterns you need to match a given sequence you want.

JavaScript regular expressions use the syntax of Perlregular expressions as a model(if you’ve used regular expressions in Perl, much of this material will be familiar.


Bit116 scripting lecture 10

Creating Powerful Patterns for Regular Expressions CONTINUED

Having had a look at the two tables on the previous slide and the boatload of special characters that are available to you, you can see there are extensive options for creating just about any pattern you need while using regular expressions.

And don't freak out!

Nobody—okay, maybe there's one or two geeks in the developer community who can pull these things out of thin air—can remember more than just a handful of these, and all developers (especially myself!) need to consult regular expression tables (by "Googling" them) in order to piece together whatever patterns are needed by the program to verify or work with strings.


Bit116 scripting lecture 10

Creating Powerful Patterns for Regular Expressions CONTINUED

  • Here's some an example how this works. Let's say you want to make sure a text field contains one or more digits, you could use the \d and + characters with the following HTML and JavaScript code, starting with the HTML code:

    • <form>

    • Enter some text: <input type="text" id="hasDigits">

    • <input type="button" id="btn1" value="Test">

    • </form>

  • Next, the JavaScript code:

    • vartestButton= document.getElementById("btn1");

    • testButton.onclick= function() {

    • varhasNum= document.getElementById("hasDigits").value;

    • vartoMatch= /\d+/;

    • if(toMatch.test(hasNum)) {

    • window.alert("Your entry contained one or more numbers!");

    • }

    • else {

    • window.alert("Your entry did not contain any numbers!");

    • }

    • }


Bit116 scripting lecture 10

Creating Powerful Patterns for Regular Expressions CONTINUED

  • This code simply checks to see whether any digits are in the string.

    • vartoMatch= /\d+/;

  • Here's what it means:

  • The first / and last /forward-slashes lets the code know this is a regular expression

  • the \dfinds a match if there is at least a one numeric character in the entry

  • the +finds a match if there is more than one numerical characters in the entry


Bit116 scripting lecture 10

Creating Powerful Patterns for Regular Expressions CONTINUED

  • If you want to ensure that the viewer typed in only digits without any other types of characters, you need to be sure the regular expression is written to test from the beginning to the end of the string.

  • Using the ^and $symbols you can ensure that the string is tested for the match starting at the beginning of the string and ending at the end of the string.

  • Thus, the following patterns would allow only digits:

    • vartoMatch= /^\d+$/;

  • The first / and last / lets the code know this is a regular expression

  • The ^ matches at the beginning of the entry (if we removed the ^ it could have a non-numeric character at the beginning but not at the end)

  • the \d matches if there is at least one numeric character

  • the + matches if there is more than one numerical characters

  • the $ matches at the end of the entry (if we removed the $ it could have a non-numeric character at the end but not at the beginning)

  • Since the only valid characters from the beginning to the end of the string are digits, this will return trueonly for entries containing digitswithout other characters present in the string.


Bit116 scripting lecture 10

Grouping Regular Expressions

You will notice in the regular expression tables above that an expression surrounded by parentheses indicates a group that can be stored for later use in the expression (or using a method such as the match() method where it will store each match of a group along with the overall match in an array).

For example, you might decide to use a particular sequence of numbers and to have that sequence repeat a particular number of times. To match the number of times something is repeated, you can use curly brackets {}along with a number or number range.

For instance, if you want to match five instances of the number 3, you could use the following expression: /3{5}/

If you wanted this to be a match if the number 3 occurs at least five times but no more than eight times, you could use the following expression: /3{5,8}/ [Note: this one might not be supported by your browser]

Now, suppose you wanted the match to start with a 3 and have any digit as the next character, and wanted to match that entire sequence five times (thus, something like 3234353637 would be a match). You might write the following: /(3\d){5}/ [this is grouping the 3 with a second digit sequence 5 times]


Bit116 scripting lecture 10

The replace() Method

  • To replace information in a string, you can use regular expressions and the replace() method of the String object.

  • The syntax for using the replace() method is as follows:

    • varName= stringName.replace(regex,newRtring);

  • You replace varNamewith the name of the variable that will hold the new string value once the information has been replaced.

  • You replace stringNamewith the name of the string variable that will undergo the replacement.

  • You replace regex with the name of the regular expression to be used to match against the string.

  • Finally, you replace newStringwith the string or string variable to replace any matched values in the string.

http://www.w3schools.com/jsref/jsref_replace.asp


Bit116 scripting lecture 10

The replace() Method CONTINUED

  • As an example, the following code replaces the first instance of “car” in myString with “skunk”:

    • varmyString = "I like the way a new car smells, and cars are fun.";

    • vartoReplace = /car/;

    • varnewString = myString.replace(toReplace,"skunk");

    • window.alert(newString);

  • The preceding code replaces only the first instance of car, giving the alert “I like the way a new skunk smells, and cars are fun.”

  • If you want to change every instance of “car” instead, the gflag is helpful at the end of the regular expression, as shown in the following code:

    • varmyString = "I like the way a new car smells, and cars are fun.";

    • vartoReplace = /car/g;

    • varnewString = myString.replace(toReplace,"skunk");

    • window.alert(newString);

  • The g flag will match every instance of the regular expression it finds in the string. The viewer will see this alert: “I like the way a new skunk smells, and skunks are fun.”


Bit116 scripting lecture 10

The replace() Method CONTINUED

  • You could also use the replace() method to make a name-changing script that is shorter and somewhat less complex than the charat_substring.html example in today's Example Files. By using the replace() method with a regular expression, the first letter of the first and last name can be changed more easily. The following code shows how:

    • function getName() {

    • vartoMatch = /^[A-Za-z]+\s[A-Za-z]+$/;

    • vartoReplace = /\b[A-Za-z]/gi;

    • vartheName = window.prompt("Enter your first and last name","");

    • if (toMatch.test(theName)) {

    • newName = theName.replace(toReplace,"Z");

    • window.alert("Now your name is " + newName);

    • }

    • else {

    • window.alert("Name invalid. Please Try Again");

    • getName();

    • }

    • }

    • getName();


Bit116 scripting lecture 10

The match() Method

  • The match() method compares a regular expression and a string to see whether they match. It returns an array containing one or more matches, depending on how it is used. If no match is found, it returns –1. The basic use of the match() method is as follows:

    • string.match(regex);

  • The string will be your string literal, and regex will be your regular expression literal. Note the difference in the order between this method and the test() method. You could use it in this way:

    • varmyString= "I am Ironman!";

    • vartoMatch= /Iron/;

    • if (myString.match(toMatch)) {

    • window.alert("The string contains Iron!");

    • }

    • else {

    • window.alert("Sorry, no Iron in the string.");

    • }

  • If this is used with the g flag or with grouping using (), it will remember each match made (including matches on groups or nested groups) and return each match as an array element.


Bit116 scripting lecture 10

The search() Method

  • The search() method executes the search for a match between a regular expression and a specified string. If a match is found, it returns the position in the string where the beginning of the match was found. Otherwise, it returns –1.

  • Here is an example of this method in action:

    • varmyString= "I am Ironman!";

    • vartoMatch= /Iron/;

    • if (myString.search(toMatch)) {

    • window.alert("Iron found at position "+ myString.search(toMatch) + "!");

    • }

    • else {

    • window.alert("Sorry, no Iron found in the string.");

    • }

  • As you can see, the syntax is much like that of the match() method.


Bit116 scripting lecture 10

Recommended Links

  • Premier Site about Regular Expressions: http://www.regular-expressions.info/

  • Mozilla Site: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

  • Regular Expression Patterns: http://www.javascriptkit.com/javatutors/redev2.shtml

  • VisiBone Regular Expressions Cheat Sheets: http://www.visibone.com/regular-expressions/

  • EloquentJavaScript: http://eloquentjavascript.net/chapter10.html

  • JavaScript Info: http://javascript.info/tutorial/regular-expressions-javascript

  • Regular Expression Tester: http://regexpal.com/


Bit116 scripting lecture 10

Lecture 10

Please begin working on the LECTURE 10 In-Class Exercises.

When you have completed your ICE, call the Instructor over to verify your work. If you have questions about your work, please call over the Instructor to clarify.

Once you have completed your ICEs, you are free to go for the day.

If you don't finish your ICEs by the end of class, you will still get full credit for actively doing the work, but it is greatly recommended you finish any outstanding ICEs outside of class.


  • Login