- Create a CSS class named image100 that sets the width of an image to 100px.
How do you use such a class? Answer:
// Class definition:
.image100 { width: 100px; }
// Class usage in img element:
<img class="image100" src="image1.jpg">
- What is the difference between a function and a method?
Answer: a function is standalone, for example: var n = parseInt("345");
A method is called from a class or an object. For example:
Math.random( ) or s.toUpperCase( ).
- For a function or method, what is the difference between a parameter and an argument?
Answer: a parameter is passed in to a function when it is defined. For example:
function celToFahr(cel) {
return 9.0 * cel / 5 + 32;
}
It tells the function what to do with the value passed in. An argument is the value that
is passed in to a function when it is invoked (or called). For example:
console.log(celToFahr(20));
// Output: 68.
- What is the difference between var and let?
Answer: a function defined with var is defined everywhere in the function where it is defined,
for example:
var n = 45;
A variable defined with let is valid anywhere in the block where it is defined,
for example:
let n = 45;
A block is a source code fragment delimited with curly braces. Here are the
two examples shown in class:
for(let i = 1; i <= 5; i++) {
let n = 2 * i + 1;
console.log(i + " " + n);
}
console.log(i + " " + n);
// Output:
1 3
2 5
3 7
4 9
5 11
After the for loop:
Error: i and n are both undefined.
for(var i = 1; i <= 5; i++) {
var n = 2 * i + 1;
console.log(i + " " + n);
}
console.log(i + " " + n);
// Output:
1 3
2 5
3 7
4 9
5 11
5 11
- How do you obtain a value from an object literal, given the key for the value?
Answer: If the object literal student1 is defined as
var student1 = { name: "Alice", year: 2, gpa: 3.89 };
// Method 1:
var n = student1.name;
// Method 2:
var n = student1["name"];
You must use Method 2 when the key contains special characters or when the
key is a variable:
var headerInfo = { "Content-Type", "text/html" };
console.log(headerInfo["Content-Type"]);
var key = "year";
console.log(student1[key]);
- We know how the of operator works for an array:
var a = [2, 3, 5, 7, 11, 13];
for(let n of a) {
console.log(n);
}
How does the in operator work?
Answer: You can use the in operator to determine if a given key is present in
an object literal:
console.log("year" in student1);
console.log("gender" in student1);
// Output:
true
false
The in operator can also be used in a for loop
sequentially process all of the
keys in an object:
for(key in student1) {
console.log(key + student1[key]);
}
// Output:
name Alice
year 11
gpa 3.89
We have seen the of operator used in a modern for loop to
sequentially process the values in an array:
var a = [39, 51, 74];
for(let n of a) {
console.log(n);
}
// Output:
39
51
74
Interestingly, using in instead of
in a for loop gives this result:
var a = [39, 51, 74];
for(let n in a) {
console.log(n);
}
// Output:
0
1
2
This tells us that the indices of the array can be considered to be the keys
(0, 1, 2) that are used to
obtain the array values (39, 51, 74).
- How do you make the value in a textfield on an input form required?
Answer:
add the required attribute to the textfield:
<input type="text" required name="fname">
- Add delete capability to the Elements Example: when the route
localhost:3000/elements/delete/5
is entered, where 5 is a parameter, row 5 is deleted from the table of elements on the
index view. Answer: here are the additions to the source code files:
Add this app.get method to the main.js script:
---------------------------------------------
app.get("/elements/delete/:aNum", (req, res) => {
// Obtain the parameter like this:
var n = req.params.aNum;
if (1 <= n && n <= 8) {
// Row numbers are zero-based so they are
// one less than the atomic number.
elements.splice(n - 1, 1);
res.render("index", { elements: elements });
}
else {
res.send("Atomic number out of range.");
}
});
- Look at the TestEjs5 Example. Modify it so that the form
uses method="post". Here is are the modified source code files. Test them.
Here are the source code files:
-------------------------------------------------
// Display a name obtained from an input form with
// method=GET
// Source code file: main.js
const express = require("express");
const app = express( );
app.use(express.urlencoded({extended: false}));
app.set("view engine", "ejs");
app.get("/contact_info", (q, r) => {
r.render("contact-info");
});
app.post("/contact_receipt", (q, r) => {
console.log(q.body);
r.render("contact-receipt", q.body);
});
app.listen(3000, ( ) => {
console.log("Listening on port 3000.");
});
-------------------------------------------------
// Source code file:
<!DOCTYPE html>
<!-- Source code file: contact-info.ejs -->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TestEjs2 Example</title>
</head>
<body>
<h2>TestEjs5 Example</h2>
<form name="form1"
action="/contact_receipt"
method="post">
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last Name:</label><br>
<input type="text" id="lname" name="lname"><br><br>
<label for="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br><br>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br><br>
<input type="submit" value="Submit Contact Info">
</form>
</body>
</html>
-------------------------------------------------
// Source code file:
<!DOCTYPE html>
<!-- Source code file: contact-receipt.ejs -->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TestEjs5 Example</title>
</head>
<body>
<h1>TestEjs5 Example</h1>
<p>Your contact information has been received<br>
Thank you for your information.</p>
<table>
<tr>
<th>First Name</th> <th>Last Name</th>
<th>Phone</th> <th>Email</th>
</tr>
<tr>
<td><%= fname %></td> <td><%= lname %></td>
<td><%= phone %></td> <td><%= email %></td>
</tr>
</table>
</body>
</html>
------------------------------------------------
- Try out the NVDA (Nonvisual Desktop Access) Screen Reader on the input form
in Exercise 7.
- You can download NVDA from
www.nvaccess.org/download/
if you want to try it out.
- For a blind person, it is not practical to use a mouse. Instead, shortcut
keyboard keys are used to navigate in screen applications, notably the Tab key.
- To start NVDA: Control + Alt + N
- To close NVDA: Insert + Q
- There are many keyboard shortcuts that can be used to navigate through applications
such as browsers. Search online for them if you are interested.
- For example:
To open a browser: Control + N
To close the current window: Alt + F4 or Alt + Fn + F4
- Recall that the required attribute for an input element insures that the form
cannot be submitted if that element is empty. The pattern attribute insures that
the input in an input element matches the pattern of a regular expression.
- A regular expression represents a pattern that is to be matched.
- Regular expressions are related to regular languages, which are defined by
finite state machines.
- RegexValidation Example. Try out this example, which shows how to use
a regular expression to validate a three letter country code. (The regular expression only
checks that the country code is three uppercase letters.
- Directions:
- Create a node project in the folder regex-validation.
- Install Express and EJS.
- Create a main.js script with these lines:
// Source code file: main.js
const express = require("express");
const app = express( );
app.set("view engine", "ejs");
app.get("/form", (q, r) => {
r.render("form1");
});
app.get("/receipt", (q, r) => {
console.log(q.query);
var cc = q.query.country_code;
r.send(`<p>SSN: ${cc}</p>`);
});
app.listen(3000, ( ) => {
console.log("Listening on port 3000);")
});
- Create the EJS file form1.ejs with this source code:
<!DOCTYPE html>
<!-- Source code file: views/form1.ejs
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form name="form1" action="/receipt"
method="get">
<label for="country_code">Country Code:</label>
<input type="text" id="country_code"
name="country_code" pattern="^[A-Z]{3}$"
title="Three letter country code"><br><br>
<input type="submit">
</form>
</body>
</html>
- Start the server: node main.js.
- In the regular expression ^[A-Z]{3}$, the
^ means start the match at the
beginning of the input expression, [A-Z] means the expression should contain
a letter between A and Z,
{3} means that there are three such letters,
$ means
end the match at the end of the expression.
- Together ^ and $ mean the expression should match the entire input. Otherwise
the match is for a substring in the input.
- Here is a regular expression that matches a U.S. social security number:
^\d{3}-\d{2}-\d{4}$
For example, 123-45-6789. \d means any digit.
- Consider the regular expression defined by
var re1 = new RegExp("abc");
- We want to check if the pattern "abc" is contained in the string
var s = "rwdabdoecsabcdejwisa";
- Here is how we check:
console.log(re1.test(s));
// Output: true
- By contrast, the pattern "abc" is not found in the string:
var t = "wihdkvndkdmablkdabdwu";
Here is the test:
console.log(re1.test(t));
// Output: false
- Usually we use this shorthand representation for
a regular expression:
var re1 = /abc/;
which means exactly the same thing as
var re1 = new RegExp("abc");
- Sometimes we want to know where the match occurs:
console.log(s.search(re1) + " ");
console.log(t.search(re1));
// Output: 10 -1
- The preceding searches could have just as easily been
performed with the String indexOf method:
console.log(s.indexOf("abc") + " ");
console.log(t.indexOf("abc"));
// Output: 10 -1
- The power of regular expressions is shown when the pattern is
more complicated:
// /[0-9]/ represents any digit from 0 to 9 inclusive.
var re2 = /[0-9]/;
s = "djfk74dk97";
console.log(re2.text(s) + " " s.search(re2));
// Output: true 4
- An equivalent representation of /[0-9]/ is
/\d/ (any digit):
var re2 = /\d/;
s = "djfk74dk97";
console.log(re2.test(s) + " " + s.search(re2));
// Output: true 4
- A token is a symbol or combination of symbols that has a specific meaning in a computer language.
- Here are some regular expression tokens for groups of characters:
\d Any digit character.
Same as [0-9].
\D Any
character that is not a digit.
\w
Any word character: Same as [A-Za-z0-9].
\W Any character that is not a word character.
\s Any whitespace character: space, new line (\n), tab
(\t),
etc.
\S Any
non-whitespace character.
.
Any character except a newline.
- Tokens that indicate repetition:
? Repeat 0 or 1 time.
+ Repeat 1 or more times.
* Repeat 0 or more times.
{n}
Repeat exactly n times.
{n,m} Repeat between n and m
times, inclusive.
{,m} Repeat from 0 to n
times, inclusive.
{n,} Repeat at least n
times.
- Some miscellaneous regular expression tokens:
| Or.
^(carat) Match must start at beginning of string.
$ Match must end at end of string.
- Some Regular Expression Tokens
- Practice Problems:
Write and test regular expressions that match
the entire input string for each of the following.
Use ^ to
force match to start at beginning of the string; use $ to
force match to end at the end of the string.
- U.S. 5 digit zipcode E.g., 60604.
var re1 = /^\d{5}$/;
var s1 = "60604";
var s2 = "606959";
console.log(re1.test(s1) + " " + re1.test(s2) + "<br>");
// Output: true false
- U.S. 5 digit zipcode with optional 4 digit extension E.g., 60604-1234.
var re2 = /^\d{5}(-\d{4})?$/;
var t1 = "60604";
var t2 = "606959";
var t3 = "60604-3456";
console.log(re2.test(t1) + " " + re2.test(t2) + " " +
re2.test(t3) + "<br>");
// Output: true false true
- U.S. social security number. E.g., 123-345-4567.
var re3 = /\d{3}-\d{2}-\d{4}/;
var u1 = "456-56-8765";
var u2 = "432-456-4958";
console.log(re3.test(u1) + " " + re3.test(u2));
// Output: true false
- U.S. phone number: (312)549-5432.
var re4 = /^(\(\d{3}\)|\d{3}\/)\d{3}-\d{4}$/;
var v1 = "(312)/362-6101";
var v2 = "312.362.6101
console.log(re4.test(v1) + " " + re4.test(v2));
// Output: true false
- Sequence of DNA patterns consisting of letters
A (adenine), C (cytosine), G (guanine), and T (thymine). E.g., AGCTTGCAT.
var re5 = /^[ACGT]+$/;
var w1 = "AGCTTGCAT";
var w2 = "AGCTTFGCAT";
console.log(re5.test(w1) + " " + re5.test(w2));
// Output: true false
- 24 hour time. E.g., 20:45:03.
var re6 = /^([01]\d|2[0-3])(:[0-5]\d){2}$/;
var x1 = "20:45:03";
var x2 - "20:45:9";
console.log(re6.test(x1) + " " + re6.test(x1));