var str = "Gluckenheimer";
var position = str.search(/n/);
/* position is now 6 */
===== The replace function =====
''replace(pattern, string)''
* Finds a substring that matches the pattern and replaces it with the string (''g'' modifier can be used)
* ''g'' modifier means "//replace globally//", all matched strings will be replaced.
* Matched substrings are returned in special variables ''$1'', ''$2'', etc.
===== The replace function: example =====
var str = "Some rabbits are rabid";
str.replace(/rab/g, "tim");
// str is now "Some timbits are timid"
// $1 and $2 are both set to "rab"
===== The split function =====
''split(parameter)''
* Example:
var str = "grapes:apples:oranges"
var fruit = str.split(/:/)
// fruit is set to ["grapes", "apples", "oranges"]
* ''%%":"%%'' and ''/:/'' are equivalent
===== The match function =====
''match(pattern)''
* The most general pattern-matching method
* Returns an array of results of the pattern-matching operation
* With the ''g'' modifier, it returns an array of all of the substrings that matched
* Without the ''g'' modifier, first element of the returned array has the matched substring, the other elements have the values of ''$1'', ''...''
===== The match function: example =====
var str = "My 3 kings beat your 2 aces";
var matches = str.match(/[ab]/g);
//matches is set to ["b", "a", "a"]
===== Form Validation =====
Common use of JavaScript is to check validity of user inputs on forms
* avoids a trip to server that would result in an error page
* error handling is kept local
* usually triggered by //submission// button((form's ''onsubmit'' event))
* error message generated locally by writing into document object.
* This example defines a function that could be used in a registration page to check that a phone number is valid (using US conventions!) HTML5 Markup: [[http://jsfiddle.net/cpjobling/rwcce/2/|fiddle with it]] [[http://localhost:4567/eg-259/examples/lecture7/forms_check.html|forms_check.html]] Script: [[http://localhost:4567/eg-259/examples/lecture7/forms_check.js|forms_check.js]]
----
Markup:
Phone number tester
Phone Number Tester
An example of the use of Regular Expressions for form validation.
View source to see the HTML code and use your browser's development tools to view the JavaScript.
Phone numbers should match the pattern 3 digits followed by a dash followed by four
digits. The regular expression for this is /\d{3}-\d{4}/
.
The example uses the DOM 0 event model which will be discussed in the next session.
The script (validation function ''validate()'' will be explained later)
/* Function tst_phone_num
Parameter: A string
Result: Returns true if the parameter has the form of a legal
seven-digit phone number (3 digits, a dash, 4 digits)
*/
function test_phone_number(num) {
// Use a simple pattern to check the number of digits and the dash
var ok = num.search(/\d{3}-\d{4}/);
if (ok === 0) {
return true;
}
else {
return false;
}
}// end of function tst_phone_num
/* Actual form validation. Called onclick */
var validate = function() {
var phoneNumber = document.getElementById("phone_number");
if (test_phone_number(phoneNumber.value)) {
return true;
} else {
alert("Phone number is invalid. Please use format ddd-dddd.");
// prevent submission
return false;
}
};
Test code for ''tst_phone_num''
// Test test_phone_number
var test_phone_number_test = function() {
var tests = ["444-5432", "444-r432", "44-1234"];
for (i = 0; i < tests.length; i++) {
var test = test_phone_number(tests[i]);
if (test) {
console.log(tests[i] + " is a legal phone number
");
} else {
console.error("Error in test_phone_number: " + tests[i] + " is not a legal phone number
");
}
}
};
===== HTML5 Pattern Attribute =====
A regular expression validator that is built-in to HTML5
* New ''pattern'' attribute can be used on some modern browsers
* Pattern text is actually evaluated as the JavaScript expression ''/^//pattern//$/'' by the JavaScript engine.
* You may need to provide a JavaScript fallback for older browsers (see later)
* E.g.
===== HTML5 Version of the Phone Number Validator =====
* [[http://localhost:4567/eg-259/examples/lecture7/forms_check_html5.html|forms_check_html5.html]]
----
Phone number tester (HTML5)
Phone Number Tester (HTML5)
An example of the use of Regular Expressions for form validation. View source to see the code.
Phone numbers should match the pattern 3 digits followed by a dash followed by four digits. The regular expression for this is
/\d{3}-\d{4}/
.
HTML5 provides a new form attribute pattern whose value is a regular expression (without the slashes). When supported,
this can be used instead of JavaScript for form validation.
In production, you would normally need to provide a JavaScript fallback for browsers that don't yet support the pattern attribute.
===== Debugging JavaScript: IE6+ =====
* Select ''Internet Options'' from the ''Tools'' menu
* Choose the ''Advanced'' tab
* Uncheck the ''Disable script debugging'' box
* Check the ''Display a notification about every script error'' box
* Now, a script error causes a small window to be opened with an explanation of the error
===== Debugging JavaScript: IE6+ (continued) =====
{{eg-259:l7-ie_script_error.png|Script error in Internet Explorer}}
===== Debugging JavaScript: Firefox =====
* Select ''Tools -> JavaScript Console''
* A small window appears to display script errors
* Remember to clear the console after correcting an error message -- avoids confusion
{{eg-259:l7-firefox_script_error.png|Script error in Firefox}}
===== Debugging JavaScript (continued) =====
* If you need to trace the execution of your scripts you need more than a JavaScript console
* Both IE6 and Firefox have JavaScript Debuggers
* In IE6 the debugger is part of the browser. See http://www.microsoft.com/scripting/debugger/default.htm for documentation.
* For Firefox (and other Mozilla-based browsers, including Netscape), the JavaScript debugger is called //Venkman// and is an optional plug in available at http://www.mozilla.org/projects/venkman/.
===== Debugging with Firebug =====
* Firefox only!
* [[http://www.getfirebug.com/|Firebug plugin]] provides sophisticated web page analysis tools including JavaScript debugging facilities and a console
* [[http://www.getfirebug.com/lite.html|Firebug Lite]] provides (limited) facilities for IE and other browsers.
* Demo
===== Debugging in WebKit Browsers =====
* Apple Safari
* Google Chrome
* Have built-in development tools
===== Summary of This Lecture =====
Text processing with //regular expressions//
* [[eg-259:lecture7#text_manipulation_in_javascript|Pattern Matching with Regular Expressions]]
* [[eg-259:lecture7#using_regular_expressions_in_javaScript|Using Regular Expressions in JavaScript]]
* [[eg-259:lecture7#form_validation|Form Validation]]
* [[eg-259:lecture7#html5_pattern_attribute|HTML5 Pattern Attribute]]
* [[eg-259:lecture7#debugging_javascript|Debugging JavaScript]]
===== Learning Outcomes ====
//At the end of this lecture you should be able to answer these questions//:
* What is a //character class// in a pattern?
* What are the //predefined character classes//, and what do they mean?
* What are the symbolic quantifiers, and what do they mean?
* Describe the two end-of-line anchors.
===== Learning Outcomes (2) ====
//At the end of this lecture you should be able to answer these questions//:
* What does the ''i'' pattern modifier do?
* What exactly does the ''String'' method ''replace'' do?
* What exactly does the ''String'' method ''match'' do?
===== Exercises =====
Write, test and debug (if necessary) HTML files that include JavaScript scripts for the following problems. When required to write functions, you must include a script to test the function with at least two different data sets.
- //Input//: A text string, using ''prompt''; //Output//: either legal name or Illegal name, depending on whether the input string fits the required format, which is: //Last name, first name, middle initial// where neither of the names can have more than 15 characters.
- //Input//: A text string, using ''prompt''; //Output//: The words of the input text, in alphabetical order
- //Function//: ''tst_name''; //Parameter//: a string; //Returns//: ''true'' if the given string has the form: ''string1, string2, letter'' where both strings must be all lowercase letters except the first letter, and //letter// must be uppercase; ''false'' otherwise.
- Use the function developed in Exercise 3 to validate a form with a text field that captures the user's name when the user presses the submit button. The form should not submit data if the name is not in the correct format. Use the example given in the session as a template.
- Repeat exercise 4 using the built-in HTML5 ''pattern'' attribute to validate the name as defined in Exercise 3.
===== More Homework Exercises =====
* Further basic JavaScript exercises, taken from Chapter 4 of Chris Bates, //Web Programming: Building Internet Applications//, 3rd Edition, John Wiley, 2006., are available. See the [[eg-259:homework:9#additional_exercises|additional exercises]] for details.
* Watch the two instructional videos on [[http://e-texteditor.com/blog/2007/regular_expressions_tutorial|Regular Expressions]] and [[http://www.digitalmediaminute.com/screencast/firebug-js/|Debugging in Firebug]].
* Work through the //[[eg-259:homework:9#practical_exercises|Practical Exercises]]//
===== What's Next? =====
Manipulating web documents through the Document Object Model (DOM) and the JavaScript event model.
* [[eg-259:lecture8#javascript_execution_environment|JavaScript Execution Environment]]
* [[eg-259:lecture8#the_document_object_model|The Document Object Model]]
* [[eg-259:lecture8#element_access_in_javascript|Element Access in JavaScript]]
* [[eg-259:lecture8#events_and_event_handling|Events and Event Handling]]
* [[eg-259:lecture8#handling_events_from_body_elements|Handling Events from Body Elements]]
* [[eg-259:lecture8#handling_events_from_button_elements|Handling Events from Button Elements]]
[[eg-259:lecture6|Previous Lecture]] | [[eg-259:home]] | [[eg-259:lecture8|Next Lecture]]