Nice book written by Danny Goodman.
1) Below table lists the regular expression pattern notation available in browsers since NN 4 and IE 4.
Character | Matches | Example |
|---|---|---|
\b | Word boundary | /\bto/ matches /to\b/ matches /\bto\b/ matches |
\B | Word nonboundary | /\Bto/ matches /to\B/ matches /\Bto\B/ matches |
\d | Numeral 0 through 9 | /\d\d/ matches |
\D | Nonnumeral | /\D\D/ matches |
\s | Single whitespace | /under\sdog/ matches "under |
\S | Single nonwhitespace | /under\Sdog/ matches |
\w | Letter, numeral, or underscore | /1\w/ matches |
\W | Not a letter, numeral, or underscore | /1\W/ matches |
. | Any character except a newline | /../ matches "Z3" |
[...] | Any one of the character set in brackets | /J[aeiou]y/ matches |
[^...] | Negated character set | /J[^eiou]y/ matches |
* | Zero or more times | /\d*/ matches |
? | Zero or one time | /\d?/ matches "" |
+ | One or more times | /\d+/ matches |
{n} | Exactly n times | /\d{2}/ matches |
{n,} | n or more times | /\d{2,}/ matches |
{n,m} | At least n, at most m times | /\d{2,4}/ matches |
^ | At beginning of a string or line | /^Sally/ matches "Sally |
$ | At end of a string or line | /Sally.$/ matches "Hi, |
2) Use the substring( ) method (in all scriptable browsers) to copy a segment starting at a particular location and ending either at the end of the string (omitting the second parameter does that) or at a fixed position within the string, counting from the start of the string:
var myString = "Every good boy does fine.";
var section = myString.substring(0, 10); // section is now "Every good"
Use the slice( ) method (in NN 4 or later and IE 4 or later) to set the end position at a point measured from the end of the string, using a negative value as the second parameter:
var myString = "Every good boy does fine.";
var section = myString.slice(11, -6); // section is now "boy does"
3) Testing String Containment with Regular Expressions
When we want to use regular expressions to know whether one string contains another.
Solution:
Create a regular expression with the short string (or pattern) and the global(g) modifier. Then pass that regular expression as a parameter to the match() method of a string value or object:
To work this regular expression mechanism into a practical function, you need some helpful surrounding code. If the string you are looking for is in the form of a string variable, you can't use the literal syntax for creating a regular expression as just shown. Instead, use the constructor function:
Example:
When matches exist, the array returned by match( ) contains the found strings. When you use a fixed string as the regular expression pattern, these returned values are redundant. That's why it's safe in the previous example to pull the first returned value from the array for display in the alert dialog box. But if you use a regular expression pattern involving the symbols of the regular expression language, each of the returned strings could be quite different, but equally valid because they adhere to the pattern.
As long as you specify the g modifier for the regular expression, you may get multiple matches (instead of just the first). The length of the array indicates the number of matches found in the longer string. For a simple containment test, you can omit the g modifier; as long as there is a match, the returned value will be an array of length 1.
4) Searching and Replacing Substrings
When we want to perform a global search-and-replace operation on a text string.
Example
<html>
<head>
<title>Recipe 1.7</title>
<link rel="stylesheet" id="mainStyle" href= type="text/css" />
<script language="JavaScript" type="text/javascript">
function doSR(form) {
var searchStr = form.srchText.value;
var re = new RegExp(searchStr, "g");
var replaceStr = form.replaceText.value;
var div = document.getElementById("boilerplate");
div.firstChild.nodeValue = div.firstChild.nodeValue.replace(re, replaceStr);
}
</script>
</head>
<body>
<h1>1.7. Searching and Replacing Substrings</h1>
<hr />
<form action="" onsubmit="return false">
Search for: <input type="text" id="srchText" name="srchText" size="30" value="\(ph\)" /><br />
Replace with: <input type="text" id="replaceText" name="replaceText" size="30" value="PLACEHOLDER REPLACEMENT" /><br />
<div class="buttons"><input type="reset" value="Reset Form" /> <input type="button" value="Search and Replace"
onclick="doSR(this.form)" /></div>
</form>
<h2>Boilerplate Text</h2>
<p id="boilerplate">Lorem ipsum dolor sit (ph) amet, consectetaur adipisicing
elit, sed (ph) do eiusmod (ph) tempor incididunt ut labore et dolore magna
aliqua. Ut enim adminim veniam, quis (ph) nostrud exercitation ullamco (ph)
laboris nisi ut aliquip ex ea commodo consequat.</p>
</body>
</html>
5) Converting Between Arrays and Strings
We want to obtain a string representation of an array's data or change a string to an array.
If you have a string with a delimiter character separating individual points of data that you want to convert to an array, specify that character as the parameter of the split( ) method of your string value or object:
Even more powerful is the split( ) method of a string value or object. You can use regular expressions as the separator parameter. For example, consider the string of comma-delimited dollar values:
Example
var amounts = "30.25,120.00,45.09,200.10";
If you want to create an array of just the integer portions of those values, you could create a regular expression whose pattern looks for a period, followed by two numerals and an optional comma (to accommodate the final entry):
var amtArray = amounts.split(/\.\d{2},?/);
6) If we want to blend two or more separate arrays into one larger array.
To join arrays together, use the concat( ) method of the array object, passing a reference to the other array as a parameter:
var comboArray = myArray.concat(anotherArray);
7) Dividing Arrays can be achieved by slice() method.
Example:
var myArray = [10, 20, 30, 40, 50, 60, 70];
var subArray = myArray.splice(0, 3);
After the splice( ) method executes, there are now two arrays as follows:
myArray = [40, 50, 60, 70]
subArray = [10, 20, 30]
One other array method, slice( ), allows you to copy a contiguous section of an array and create a separate, new array with those entries. The difference between slice( ) and splice( ) is that slice( ) does not alter the original array. Parameters to slice( ) are integers of the starting index of the group to extract and the ending index. (Or else, omit the ending index to take every entry to the end of the array.)
8) Nesting Named Functions
You want to create a function that belongs to only one other function.
Solution
Starting with IE 4 and NN 4, you can nest a function inside another function according to the following syntax model:
function myFuncA( ) {
// statements go here
function.myFuncB( ) {
// more statements go here
}
}
When you invoke myFuncA( ) from the global space, it invokes its nested function, which dutifully displays the values of the two variables that are defined in the outer and inner functions. IE behaves the same way, as expected. But in Netscape 6 or later, you can invoke the nested function from the global space by way of the outer function:
myFuncA.myFuncB( );
Because the outer function does not execute in this direct access to myFuncB, the valueA variable is not initialized with any value. When myFuncB( ) runs, it shows the value of valueB, but valueA comes back as undefined. Therefore, access to the outer function's variables is possible only when the inner function is invoked by the outer function.
9) Using a select Element for Navigation
You want users to choose a destination from a pop-up list originating from a select tag.
If you wish to bind the onchange (or other) event to the select element through other means, the event handler function cannot receive a reference to the select element as an argument. Instead, the function has to derive that information from the event object in a way that applies to both the IE and NN event models:
<html>
<body>
<form name="f">
<select name="chooser" id="chooser" onchange="navigate(event)">
<option value="">Choose a Destination:</option>
<option value="http://www.megacorp.com/index.html">Home</option>
<option value="http://www.megacorp.com/products/index.html">Products</option>
<option value="http://www.megacorp.com/support/index.html">Support</option>
<option value="http://www.megacorp.com/contact.html">Contact Us</option>
</select>
</form>
</body>
</html>
<script>
function navigate(evt) {
evt = (evt) ? evt : ((event) ? event : null);
if (evt) {
var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if (elem && elem.tagName.toLowerCase() == "select" && elem.value) {
location.href = elem.value;
}
}
}
</script>
Hope you enjoy reading the book.
About the Author
Danny Goodman has been writing about personal computers and consumer electronics since the late 1970s. In 2006, he celebrated 25 years as a freelance writer and programmer, having published hundreds of magazine articles, several commercial software products, and three dozen computer books. Through the years, his most popular book titles — on HyperCard, AppleScript, JavaScript, and Dynamic HTML — have covered programming environments that are both accessible to non-professionals, yet powerful enough to engage experts. His Dynamic HTML: The Definitive Reference, now in its third edition, is an O'Reilly bestseller.
To keep up to date on the needs of web developers for his recent books, Danny is also a programming consultant to some of the industry's top intranet development groups and corporations. His expertise in implementing sensible cross-browser client-side scripting solutions is in high demand and allows him to, in his words, "get code under my fingernails while solving real-world problems."
Danny was born in Chicago, Illinois during the Truman Administration. He earned a B.A. and M.A. in Classical Antiquity from the University of Wisconsin, Madison. He moved to California in 1983 and lives in a small San Francisco area coastal community, where he alternates views between computer screens and the Pacific Ocean.
No comments:
Post a Comment