Wednesday, September 14, 2011

JavaScript BCA 3rd Frequently Asked Questions & Answers

What are Cookies ?
Cookies are small amounts of data stored by the web browser. They allow you to store particular information about a user and retrieve it every time they visit your pages. Each user has their own unique set of cookies.
Cookies are typically used by web servers to perform functions such as tracking your visits to websites, enabling you to log in to sites, and storing your shopping cart. However we don't need fancy web server programming to use cookies. We can use them in JavaScript, too!

Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after completing many pages. But how to maintain user's session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
How It Works ?
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields:
• Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
• Domain : The domain name of your site.
• Path : The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
• Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
• Name=Value : Cookies are set and retrieved in the form of key and value pairs.
Cookies were originally designed for CGI programming and cookies' data is automatically transmitted between the web browser and web server, so CGI scripts on the server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page.
Storing Cookies:
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this:
Syntax:
document.cookie = "key1=value1;key2=value2;expires=date";
Here expires attribute is option. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and after that cookies' value will not be accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.
Example:
Following is the example to set a customer name in input cookie.





Enter name:



This will produce following result. Now enter something in the text box and press the button "Set Cookie" to set the cookies.
Now your machine has a cookie called name. You can set multiple cookies using multiplekey=value pairs separated by comma.
You will learn how to read this cookie in next section.
Reading Cookies:
Reading a cookie is just as simple as writing one, because the value of the document.cookieobject is the cookie. So you can use this string whenever you want to access the cookie.
The document.cookie string will keep a list of name=value pairs separated by semicolons, wherename is the name of a cookie and value is its string value.
You can use strings' split() function to break the string into key and values as follows:
Example:
Following is the example to get the cookies set in previous section.








Note: Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time please try to digest it.
This will produce following result. Now press the button "Get Cookie" to see the cookies which you have set in previous section.


Note: There may be some other cookies already set on your machine. So above code will show you all the cookies set at your machine.
Setting the Cookies Expiration Date:
You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiration date within the cookie. This can be done by setting the expiresattribute to a date and time.
Example:
The following example illustrates how to set cookie expiration date after 1 Month :





Enter name:



Deleting a Cookie:
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past.
Example:
The following example illustrates how to delete cookie by setting expiration date one Month in past :





Enter name:



Note: Instead of setting date, you can see new time using setTime() function.






A function is a group of reusable code which can be called anywhere in your programme. This eliminates the need of writing same code again and again. This will help programmers to write modular code. You can divide your big programme in a number of small and manageable functions.
Like any other advance programming language, JavaScript also supports all the features necessary to write modular code using functions.
You must have seen functions like alert() and write() in previous chapters. We are using these function again and again but they have been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section will explain you how to write your own functions in JavaScript.
Function Definition:
Before we use a function we need to define that function. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here:

Example:
A simple function that takes no parameters called sayHello is defined here:

Calling a Function:
To invoke a function somewhere later in the script, you would simple need to write the name of that function as follows:

To understand it in better way you can Try it yourself.
Function Parameters:
Till now we have seen function without a parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters.
A function can take multiple parameters separated by comma.
Example:
Let us do a bit modification in our sayHello function. This time it will take two parameters:

Note: We are using + operator to concatenate string and number all together. JavaScript does not mind in adding numbers into strings.
Now we can call this function as follows:

To understand it in better way you can Try it yourself.
The return Statement:
A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.
For example you can pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program.
Example:
This function takes two parameters and concatenates them and return resultant in the calling program:

Now we can call this function as follows:

To understand it in better way you can Try it yourself.
Advanced Concepts for Functions:
There is lot to learn about JavaScript functions. But I have put following important concepts in this tutorial. If you are not in furry then I would suggest to go through them at least once.
• JavaScript Nested Functions
• JavaScript Function( ) Constructor
• JavaScript Function Literals









What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page.
When the page loads, that is an event. When the user clicks a button, that click, too, is an event. Another example of events are like pressing any key, closing window, resizing window etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable to occur.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element have a certain set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see few examples to understand a relation between Event and JavaScript:
onclick Event Type:
This is the most frequently used event type which occurs when a user clicks mouse left button. You can put your validation, warning etc against this event type.
Example:








This will produce following result and when you click Hello button then onclick event will occur which will trigger sayHello() function.
To understand it in better way you can Try it yourself.
onsubmit event type:
Another most important event type is onsubmit. This event occurs when you try to submit a form. So you can put your form validation against this event type.
Here is simple example showing its usage. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true the form will be submitted otherwise it will not submit the data.
Example:





.......



onmouseover and onmouseout:
These two event types will help you to create nice effects with images or even with text as well. The onmouseover event occurs when you bring your mouse over any element and theonmouseout occurs when you take your mouse out from that element.
Example:
Following example shows how a division reacts when we bring our mouse in that division:





This is inside the division



To understand it in better way you can Try it yourself.
You can change different images using these two event types or you can create help baloon to help your users.
HTML 4 Standard Events
The standard HTML 4 events are listed here for your reference. Here script indicates a Javascript function to be executed agains that event.
Event Value Description
onchange script Script runs when the element changes
onsubmit script Script runs when the form is submitted
onreset script Script runs when the form is reset
onselect script Script runs when the element is selected
onblur script Script runs when the element loses focus
onfocus script Script runs when the element gets focus
onkeydown script Script runs when key is pressed
onkeypress script Script runs when key is pressed and released
onkeyup script Script runs when key is released
onclick script Script runs when a mouse click
ondblclick script Script runs when a mouse double-click
onmousedown script Script runs when mouse button is pressed
onmousemove script Script runs when mouse pointer moves
onmouseout script Script runs when mouse pointer moves out of an element
onmouseover script Script runs when mouse pointer moves over an element
onmouseup script Script runs when mouse button is released


















Every web page resides inside a browser window which can be considered as an object. A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.
The way that document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.
• Window object: Top of the hierarchy. It is the outmost element of the object hierarchy.
• Document object: Each HTML document that gets loaded into a window becomes a document object. The document contains the content of the page.
• Form object: Everything enclosed in the
...
tags sets the form object.
• Form control elements: The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes.
Here is a simple hierarchy of few important objects:

There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify document content.
• The Legacy DOM: This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.
• The W3C DOM: This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers.
• The IE4 DOM: This document object model was introduced in Version 4 of Microsoft's Internet Explorer browser. IE 5 and later versions include support for most basic W3C DOM features.
DOM compatibility
If you want to write a script that uses the W3C DOM when it is available, and otherwise uses the IE 4 DOM if it is available, you can use a capability-testing approach that first checks for the existence of a method or property to determine whether the browser has the capability you desire. For example:
if (document.getElementById) {

// If the W3C method exists, use it

}

else if (document.all) {

// If the all[] array exists, use it

}

else {

// Otherwise use the legacy DOM

}


With Statement in javaScript ?

Explanation
"with" statement is used when numerous function of an object is used or a function of an object is to be used numerous times.

Syntax:
with(object)
{
// Calling the functions or methods of the object
}

For this example we will use the object "document" and its methods (functions) "write" and attribute "title".
Example Code:


Result:
inside with statement
using with(object) we can call its functions directly
TITLE - With Statement Code - Javascript (JS) Tutorial

In the above example you can clearly see that the write function is executed numerous times with out calling document.write() and also title (document.title) is called. You can use any objects with "with" statement. e.g: date, math, etc.



Using 'for' loop in javascript?
I want to execute the same set of statements numerous time based on a incremental or decremental value?



Explanation

for LOOP:
As we state it, for loop is a looping syntax.
A set of statements are executed as a loop until a condition is satisfied, the condition is based on an incremental or decremental counter. In other words "Looping statements in javascript are used to execute the same set of code a specified number of times".

Syntax:
for(intialvalue; condition; increment)
{
// set of statements that will be executed
}

As defined in the syntax, for loop takes three parameters, the initial value (e.g i=0), condition - the statements inside "for" will be executed until this condition is satisfied (e.g i<7), increment - this is where we set the initial value to be increased or decreased after each loop. All the three parameters are separated by semicolon ";". For an example, we will consider a situation where we want to add all numbers between one and ten. Example Code:

Result:
--------- The total ------: 45

The example worked as follows,
a) Initially we created the for loop by setting variable i as 1.
b) then we set the condition that the loop should execute till i is less than 11 (i<11). c) We made the variable to be incremented at the end of each loop (i++) First loop: i=0, i<11 is true so the statement is executed, now the total becomes 0+1=1 and i is incremented to 2. Second loop: now i=1, i<11 is true so the statement is executed, now the total becomes 1+2=3 and i is incremented to 2. this continues till i=11 Last loop: now i=11, i<11 becomes false and the loop ends here. Note: i++ increments the value at the end on the loop, while ++i to increase the value of i at the start of the loop. Using While loop in javascript? Explanation 'while' loop is used to execute a set of statements repeatedly until a condition works true. The difference between 'for' and 'while' loop is that 'while' does not take counter as an argument. Syntax: while(condition) { // set of statements that will be executed } As defined in the syntax, while loop has only one parameter, condition to be validated. The statements inside "while" will be executed until this condition becomes false. For an example, we will consider a situation where we want to print first 5 number. Example Code:

Result:
The value of i is - 0
The value of i is - 1
The value of i is - 2
The value of i is - 3
The value of i is - 4


The execution process is as,
a) The initialization of the variable "i" as 1 was done before starting the loop.
b) In while loop, the condition was checked,
the condition is satisfied (true) as i<5 and so the statements are executed. c) In the last line of the statement we has increased or incremented the value of i by 1. So after the end of the loop the pointer goes back to the beginning of the loop and checks the condition. d) Now "i" will be 1 and i is less than 5. The condition satisfies and the statements are executed. This continues till i is 5. e) When i is five, the condition becomes false and the pointer comes out of the loop. Using do-while loop in javascript? Difference between while and do-while? Explanation 'do-while' loop is similar to while loop and the only difference here is that the set of statements are executed first and the condition is checked next. Syntax: do { // set of statements that will be executed } while(condition) Here the statements are added under do loop and while condition is checked at the end of loop. In 'Do While' the statements are executed once even if the condition will fail. An example Example Code:

Result:
Testing DO-While loop

In the example the condition is 'i' should not be equal to zero. The statements are executed and the condition is checked. The condition failed. The pointer comes out of the loop. So the statements are executed once even when the condition fails.







Garbage Collection:-
Garbage collection (GC) is a form of automatic memory management. It is a special case of resource management, in which the limited resource being managed is memory. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program.

It works like this:
• Every variable which is "in scope" is called a "scavenger". A scavenger may refer to a number, an object, a string, whatever. We maintain a list of scavengers -- variables are moved on to the scav list when they come into scope and off the scav list when they go out of scope.
• Every now and then the garbage collector runs. First it puts a "mark" on every object, variable, string, etc – all the memory tracked by the GC. (JScript uses the VARIANT data structure internally and there are plenty of extra unused bits in that structure, so we just set one of them.)
• Second, it clears the mark on the scavengers and the transitive closure of scavenger references. So if a scavenger object references a nonscavenger object then we clear the bits on the nonscavenger, and on everything that it refers to. (I am using the word "closure" in a different sense than in my earlier post.)
• At this point we know that all the memory still marked is allocated memory which cannot be reached by any path from any in-scope variable. All of those objects are instructed to tear themselves down, which destroys any circular references.

Garbage collection was invented by John McCarthy around 1959 to solve problems in Lisp.
Garbage collection is often portrayed as the opposite of manual memory management, which requires the programmer to specify which objects to deallocate and return to the memory system. However, many systems use a combination of the two approaches, and other techniques such as stack allocation and region inference can carve off parts of the problem. There is an ambiguity of terms, as theory often uses the terms manual garbage collection and automatic garbage collection rather than manual memory management and garbage collection, and does not restrict garbage collection to memory management, rather considering that any logical or physical resource may be garbage collected.
Garbage collection does not traditionally manage limited resources other than memory that typical programs use, such as network sockets, database handles, user interaction windows, and file and device descriptors. Methods used to manage such resources, particularly destructors, may suffice as well to manage memory, leaving no need for GC. Some GC systems allow such other resources to be associated with a region of memory that, when collected, causes the other resource to be reclaimed; this is called finalization. Finalization may introduce complications limiting its usability, such as intolerable latency between disuse and reclaim of especially limited resources, or a lack of control over which thread performs the work of reclaiming.
Scripting Myth & script security
Scripting Myth :-Despite being the world’s most widely-used programming language, JavaScript is the most misunderstood and undervalued. The situation has improved during the past few years, but these myths still permeate the IT world.
1. JavaScript == Java
UK developer Jeremy Keith devised the best explanation:
Java is to JavaScript as ham is to hamster
The names are confusingly similar but Java and JavaScript are not related. There are a number of superficial similarities, but the same can be said for any language adopting a C-like syntax.
The language was originally named Mocha, became LiveScript, and finally JavaScript at a time when Java was heralded as the savior to life, the universe and everything. The name reflected Netscape’s marketing efforts — not any underlying relationship.
2. JavaScript is a “toy” language
The “script” part of the name gives the impression that JavaScript is some type of cut-down, macro-like or less capable version of Java. It’s not. If anything, popular JavaScript features such as closures and lambda functions are now finding their way into other languages (PHP, C# and Java itself).
JavaScript is most commonly found as a browser-based interpreted language, but that doesn’t mean it’s any less powerful or competent than an OS-based compiled language.
3. JavaScript is only found in browsers
Most people experience JavaScript as an embedded browser language but it (or languages based on the ECMAScript standard) can be found in many other places, e.g.
 Mozilla’s Firefox browser and Thunderbird email client use JavaScript for some application processes
 Flash ActionScript is based on JavaScript
 PDF files can have JavaScript embedded
 many Microsoft and Apple desktop widgets use JavaScript
 OpenOffice.org provides JavaScript support
 webOS, used in Palm mobiles, uses JavaScript for its application framework
 JavaScript can be used as an application programming language on the GNOME desktop and as a scripting language in Windows.
JavaScript does not have a strong server-side presence but several dozen implementations exist. The day we’ll be able to develop JavaScript on the client and the server can’t come soon enough!
4. JavaScript is inconsistent and buggy
Those days are long gone. Browser vendors adhere to an agreed standard (ECMAScript) and JavaScript-specific issues are rare.
However, browser features are not always consistent: DOM manipulation particularities, event handling idiosyncrasies, and browser quirks all cause development headaches. That’s not a fault with the language itself, but the browser objects you can access with JavaScript.
5. JavaScript is not object-orientated
Confusion arises because JavaScript does not provide obvious class-orientated inheritance. The lack of a ‘class’ keyword causes many developers to assume JavaScript is a functional language.
JavaScript offers prototypal inheritance. The real beauty is that you can write functional language code or use classical inheritance patterns with private properties and methods.
Furthermore, everything in JavaScript is an object — including native types and functions. How many other languages offer constructs such as:
view plainprint?
1. var x = new Number(123);
2. var opp = "oops".substr(0,3);
3. var f = function() { return function() { alert("hello!"); }; };
What about passing a function as a parameter (it’s just another object)…
view plainprint?
1. var Add = function(a, b) { return a + b; };
2. function Calculate(func, a, b) {
3. return func(a, b);
4. }
5. var s = Calculate(Add, 1, 2); // s = 3
Or perhaps extending native types…
view plainprint?
1. // reverse any string
2. String.prototype.Reverse = function() {
3. return this.split("").reverse().join("");
4. };
5. var h1 = "Hello!";
6. var h2 = h1.Reverse(); // !olleH
JavaScript can be a little confusing at first but you’ll miss its elegance and power when you return to other languages.
script security:-
JavaScript is designed as an open scripting language. It is not intended to replace proper security measures, and should never be used in place of proper encryption. See also my article about cross site scripting.
JavaScript has its own security model, but this is not designed to protect the Web site owner or the data passed between the browser and the server. The security model is designed to protect the user from malicious Web sites, and as a result, it enforces strict limits on what the page author is allowed to do. They may have control over their own page inside the browser, but that is where their abilities end.
• JavaScripts cannot read or write files on users' computers (File API - not currently supported by many browsers - allows files to be read by scripts if the user specifically chooses to allow it), though they can cause the browser to load remote pages and resources like scripts or images, which the browser may choose to cache locally. They cannot create files on the server (except by communicating with a server side script that creates files for them). The only thing they can store on the user's computer are cookies (and Web Storage - similar to cookies but with more data types - in newer browsers).
• They are allowed to interact with other pages in a frameset, if those frames originate from the same Web site, but not if they originate from another Web site (the postMessage method from HTML 5 does safely extend this capability, but I will not cover that here). Some browsers will even treat different port numbers on the same server as a different Web site.
• JavaScript cannot be used to set the value attribute of a file input, and will not be allowed to use them to upload files without permission.
• JavaScript cannot read what locations a user has visited by reading them from the location object, although it can tell the browser to jump back or forward any number of steps through the browser history. It cannot see what other Web pages the user has open.
• JavaScript cannot access the cookies or variables from other sites.
• It cannot see when the user interacts with other programs, or other parts of the browser window.
• It cannot open windows out of sight from the user or too small for the user to see, and in most browsers, it cannot close windows that it did not open.
Most people who want to know about security with JavaScript are interested in producing password protected pages or sending encrypted data to or from the user's computer. For true security, use SSL/TLS (HTTPS) and put all of your checks on the server. You could also use a security lockout if too many false attempts are made, preventing brute force cracks. JavaScript cannot replace this functionality. The problem lies in the fact that if a person can read what you are sending over the internet, they can also rewrite it. So when you think you are filling in a password to access a protected page, they have changed it so that you are actually filling in a password that will be sent to them. This requires SSL to be sure that you are protected. Still, this tutorial is about JavaScript, so I will now show you what can and cannot be done with JavaScript.





JavaScript Features
In this JavaScript tutorial, you will learn about features of JavaScript, JavaScript as a programming tool, dynamic effects, browser detection, DOM control and other popular JavaScript features.
A Great Programming Tool for HTML:
Professional Web designers are undoubtedly adept in using HTML and proficient in website design but not necessarily skillful in computer programming. JavaScript is a programming tool for such a situation. JavaScript is a powerful scripting language that helps HTML designers to effectively and interactively design websites and web pages in a very simple and efficient way.


Handles Dynamic Effects:
JavaScript is such a powerful scripting language which has features to achieve dynamic effects in web pages. Using the features available in JavaScript, the designer can decide to have dynamically placed text at run time.


Browser Detection:
One of the powerful feature of JavaScript is its ability to detect client browser. Browser detection feature of JavaScript helps to achieve independent platforms. JavaScript can detect the type of browser the visitor is using and programatically switch the page to show customised pages designed for different browsers. Thus by making use of browser detection feature of JavaScript, the designer gets better control over the browser.


Saves Time:
JavaScript also has the feature of validating data submitted at the client level. This helps in saving the processing time of the server because JavaScript initially creates the validation on the client side.


DOM:
Client side JavaScript is embedded inside HTML This embedded JavaScript is used along with DOM (Document Object Model) for control over the browser by means of objects.


Popular Scripting language:
JavaScript has simple rules and procedures that make it easier to use and learn for programmers. This has made JavaScript a popular client-side scripting language.


Interpreted Language:
It is an interpreted language, meaning that it can be used or executed with ease without pre-compilation.


Visual JavaScript:
Visual JavaScript is a component-based visual development tool for the Netscape Open Network Environment used by programmers who want to build cross-platform web-based applications.


Generators and Iterators:
The newer version of JavaScript features built-in Generators and Iterators.

There are other important features in JavaScript such as variables, arrays, objects, methods, event handlers, etc. which will be explained in detail in the following sections of this tutorial.




Advantages and disadvantages of java script?
Advantages include Cross-browser support, validating data on the client, and being able to create more sophisticated user interfaces.
JavaScript effects are also much faster to download than some other front-end technologies like Flash and Java applets. In fact, unless you're writing a massive JavaScript application, it's quite likely that no significant extra download time will be added to a page by using JavaScript on it. Nor do users need to download a plugin before they can view your JavaScript, as they would with Flash for example, they simply need a browser that supports it - and, of course, most modern browsers do.
Other advantages include the fact that you don't need any extra tools to write JavaScript, any plain text or HTML editor will do, so there's no expensive development software to buy. It's also an easy language to learn, and there's a thriving and supportive online community of JavaScript developers and information resources.
The disadvantages of JavaScript, as with most web development, are almost entirely related to browser compatibility.
While the advances in browser programmability we've seen over recent years are, generally speaking, a good thing, if you don't implement them with care you can create a lot of inconsistencies and broken pages quite unintentionally using JavaScript. Code that works just great on IE4 might not work at all on Netscape 4, what works in NN6 doesn't always work in NN 4, and so on.
In essence, there are two main problems with JavaScript and browsers:
• The different JavaScript versions in different browsers.
• Browser programmability: the HTML elements and features of the browser that can be accessed through any scripting language. (IE4 , for example, makes most of the page and HTML accessible to scripts, but Navigator 4 limits what can be accessed and manipulated.)
it allow Developer to add Dynamic content like image swapping , Rollover, which is not available in HTML or CSS
CSS basically used for ----> styling ur pages
JavaScript used to allow ----> script access to objects embedded in other application.


Regular Expressions
Regular expressions are used to do sophisticated pattern matching, which can often be helpful in form validation. For example, a regular expression can be used to check whether an email address entered into a form field is syntactically correct. JavaScript supports Perl-compatible regular expressions.
There are two ways to create a regular expression in JavaScript:
1. Using literal syntax
var reExample = /pattern/;
2. Using the RegExp() constructor
var reExample = new RegExp("pattern");
Assuming you know the regular expression pattern you are going to use, there is no real difference between the two; however, if you don't know the pattern ahead of time (e.g, you're retrieving it from a form), it can be easier to use theRegExp() constructor.
JavaScript's Regular Expression Methods
The regular expression method in JavaScript has two main methods for testing strings: test() and exec().
The exec() Method
The exec() method takes one argument, a string, and checks whether that string contains one or more matches of the pattern specified by the regular expression. If one or more matches is found, the method returns a result array with the starting points of the matches. If no match is found, the method returns null.
The test() Method
The test() method also takes one argument, a string, and checks whether that string contains a match of the pattern specified by the regular expression. It returns true if it does contain a match and false if it does not. This method is very useful in form validation scripts. The code sample below shows how it can be used for checking a social security number. Don't worry about the syntax of the regular expression itself. We'll cover that shortly.
Code Sample: RegularExpressions/Demos/SsnChecker.html


ssn Checker







Code Explanation
Let's examine the code more closely:
1. First, a variable containing a regular expression object for a social security number is declared.
var RE_SSN = /^[0-9]{3}[\- ]?[0-9]{2}[\- ]?[0-9]{4}$/;
2. Next, a function called checkSsn() is created. This function takes one argument: ssn, which is a string. The function then tests to see if the string matches the regular expression pattern by passing it to the regular expression object's test() method. If it does match, the function alerts "VALID SSN". Otherwise, it alerts "INVALID SSN".
3. function checkSsn(ssn){
4. if (RE_SSN.test(ssn)) {
5. alert("VALID SSN");
6. } else {
7. alert("INVALID SSN");
8. }
}
9. A form in the body of the page provides a text field for inserting a social security number and a button that passes the user-entered social security number to the checkSsn() function.
10.
11.
12.
Flags
Flags appearing after the end slash modify how a regular expression works.
• The i flag makes a regular expression case insensitive. For example, /aeiou/i matches all lowercase and uppercase vowels.
• The g flag specifies a global match, meaning that all matches of the specified pattern should be returned.
String Methods
There are several String methods that use regular expressions.
The search() Method
The search() method takes one argument: a regular expression. It returns the index of the first character of the substring matching the regular expression. If no match is found, the method returns -1.
"Webucator".search(/cat/); //returns 4
The split() Method
The split() method takes one argument: a regular expression. It uses the regular expression as a delimiter to split the string into an array of strings.
"Webucator".split(/[aeiou]/);
/*
returns an array with the following values:
"W", "b", "c", "t", "r"
*/
The replace() Method
The replace() method takes two arguments: a regular expression and a string. It replaces the first regular expression match with the string. If the g flag is used in the regular expression, it replaces all matches with the string.
"Webucator".replace(/cat/, "dog"); //returns Webudogor
"Webucator".replace(/[aeiou]/g, "x"); //returns Wxbxcxtxr
The match() Method
The match() method takes one argument: a regular expression. It returns each substring that matches the regular expression pattern.
"Webucator".match(/[aeiou]/g);
/*
returns an array with the following values:
"e", "u", "a", "o"
*/
Regular Expression Syntax
A regular expression is a pattern that specifies a list of characters. In this section, we will look at how those characters are specified.
Start and End ( ^ $ )
A caret (^) at the beginning of a regular expression indicates that the string being searched must start with this pattern.
• The pattern ^foo can be found in "food", but not in "barfood".
A dollar sign ($) at the end of a regular expression indicates that the string being searched must end with this pattern.
• The pattern foo$ can be found in "curfoo", but not in "food".
Number of Occurrences ( ? + * {} )
The following symbols affect the number of occurrences of the preceding character: ?, +, *, and {}.
A questionmark (?) indicates that the preceding character should appear zero or one times in the pattern.
• The pattern foo? can be found in "food" and "fod", but not "faod".
A plus sign (+) indicates that the preceding character should appear one or more times in the pattern.
• The pattern fo+ can be found in "fod", "food" and "foood", but not "fd".
A asterisk (*) indicates that the preceding character should appear zero or more times in the pattern.
• The pattern fo*d can be found in "fd", "fod" and "food".
Curly brackets with one parameter ( {n} ) indicate that the preceding character should appear exactly n times in the pattern.
• The pattern fo{3}d can be found in "foood" , but not "food" or "fooood".
Curly brackets with two parameters ( {n1,n2} ) indicate that the preceding character should appear between n1 andn2 times in the pattern.
• The pattern fo{2,4}d can be found in "food","foood" and "fooood", but not "fod" or "foooood".
Curly brackets with one parameter and an empty second paramenter ( {n,} ) indicate that the preceding character should appear at least n times in the pattern.
• The pattern fo{2,}d can be found in "food" and "foooood", but not "fod".
Common Characters ( . \d \D \w \W \s \S )
A period ( . ) represents any character except a newline.
• The pattern fo.d can be found in "food", "foad", "fo9d", and "fo*d".
Backslash-d ( \d ) represents any digit. It is the equivalent of [0-9].
• The pattern fo\dd can be found in "fo1d", "fo4d" and "fo0d", but not in "food" or "fodd".
Backslash-D ( \D ) represents any character except a digit. It is the equivalent of [^0-9].
• The pattern fo\Dd can be found in "food" and "foad", but not in "fo4d".
Backslash-w ( \w ) represents any word character (letters, digits, and the underscore (_) ).
• The pattern fo\wd can be found in "food", "fo_d" and "fo4d", but not in "fo*d".
Backslash-W ( \W ) represents any character except a word character.
• The pattern fo\Wd can be found in "fo*d", "fo@d" and "fo.d", but not in "food".
Backslash-s ( \s) represents any whitespace character (e.g, space, tab, newline, etc.).
• The pattern fo\sd can be found in "fo d", but not in "food".
Backslash-S ( \S ) represents any character except a whitespace character.
• The pattern fo\Sd can be found in "fo*d", "food" and "fo4d", but not in "fo d".
Grouping ( [] )
Square brackets ( [] ) are used to group options.
• The pattern f[aeiou]d can be found in "fad" and "fed", but not in "food", "faed" or "fd".
• The pattern f[aeiou]{2}d can be found in "faed" and "feod", but not in "fod", "fed" or "fd".
Negation ( ^ )
When used after the first character of the regular expression, the caret ( ^ ) is used for negation.
• The pattern f[^aeiou]d can be found in "fqd" and "f4d", but not in "fad" or "fed".
Subpatterns ( () )
Parentheses ( () ) are used to capture subpatterns.
• The pattern f(oo)?d can be found in "food" and "fd", but not in "fod".
Alternatives ( | )
The pipe ( | ) is used to create optional patterns.
• The pattern foo$|^bar can be found in "foo" and "bar", but not "foobar".
Escape Character ( \ )
The backslash ( \ ) is used to escape special characters.
• The pattern fo\.d can be found in "fo.d", but not in "food" or "fo4d".
Backreferences
Backreferences are special wildcards that refer back to a subpattern within a pattern. They can be used to make sure that two subpatterns match. The first subpattern in a pattern is referenced as \1, the second is referenced as \2, and so on.
For example, the pattern ([bmpw])o\1 matches “bob”, “mom”, “pop”, and “wow”, but not "bop" or "pow".
A more practical example has to do matching the delimiter in social security numbers. Examine the following regular expression.
^\d{3}([\- ]?)\d{2}([\- ]?)\d{4}$
Within the caret (^) and dollar sign ($), which are used to specify the beginning and end of the pattern, there are three sequences of digits, optionally separated by a hyphen or a space. This pattern will be matched in all of following strings (and more).
• 123-45-6789
• 123 45 6789
• 123456789
• 123-45 6789
• 123 45-6789
• 123-456789
The last three strings are not ideal, but they do match the pattern. Backreferences can be used to make sure that the second delimiter matches the first delimiter. The regular expression would look like this.
^\d{3}([\- ]?)\d{2}\1\d{4}$
The \1 refers back to the first subpattern. Only the first three strings listed above match this regular expression.
Form Validation with Regular Expressions
Regular expressions make it easy to create powerful form validation functions. Take a look at the following example.
Code Sample: RegularExpressions/Demos/Login.html


Login

Login Form

Email:
Password:
*Password must be between 6 and 10 characters and can only contain letters and digits.

Code Explanation This code starts by defining regular expressions for an email address and a password. Let's break each one down. var RE_EMAIL = /^(\w+\.)*\w+@(\w+\.)+[A-Za-z]+$/; 1. The caret (^) says to start at the beginning. This prevents the user from entering invalid characters at the beginning of the email address. 2. (\w+[\-\.])* allows for a sequence of word characters followed by a dot or a dash. The * indicates that the pattern can be repeated zero or more times. Successful patterns include "ndunn.", "ndunn-", "nat.s.", and "nat-s-". 3. \w+ allows for one or more word characters. 4. @ allows for a single @ symbol. 5. (\w+\.)+ allows for a sequence of word characters followed by a dot. The + indicates that the pattern can be repeated one or more times. This is the domain name without the last portion (e.g, without the "com" or "gov"). 6. [A-Za-z]+ allows for one or more letters. This is the "com" or "gov" portion of the email address. 7. The dollar sign ($) says to end here. This prevents the user from entering invalid characters at the end of the email address. var RE_PASSWORD = /^[A-Za-z\d]{6,8}$/; 1. The caret (^) says to start at the beginning. This prevents the user from entering invalid characters at the beginning of the password. 2. [A-Za-z\d]{6,8} allows for a six- to eight-character sequence of letters and digits. 3. The dollar sign ($) says to end here. This prevents the user from entering invalid characters at the end of the password. Exercise: Advanced Form Validation Duration: 25 to 40 minutes. 1. Open RegularExpressions/Exercises/FormValidation.js for editing. o Write additional regular expressions to check for: 1. Proper Name  starts with capital letter  followed by one or more letters or apostophes  may be multiple words (e.g, "New York City") 2. Initial  zero or one capital letters 3. State  two capital letters 4. US Postal Code  five digits (e.g, "02138")  possibly followed by a dash and four digits (e.g, "-1234") 5. Username  between 6 and 15 letters or digits 2. Open RegularExpressions/Exercises/Register.html for editing. o Add validation to check the following fields: 1. first name 2. middle initial 3. last name 4. city 5. state 6. zip 7. username 3. Test your solution in a browser. 1. Add regular expressions to test Canadian and United Kingdom postal codes: o Canadian Postal Code - A letter followed by a digit, a letter, a space, a digit, a letter, and a digit (e.g, M1A 1A1) o United Kingdom Postal Code - One or two letters followed by a digit, an optional letter, a space, a digit, and two letters (e.g, WC1N 3XX) 2. Modify Register.html to check the postal code against these two new regular expressions as well as the regular expression for a US postal code. Where is the solution? Cleaning Up Form Entries It is sometimes nice to clean up user entries immediately after they are entered. This can be done using a combination of regular expressions and the replace() method of a string object. The replace() Method Revisited Earlier, we showed how the replace() method of a string object can be used to replace regular expression matches with a string. The replace() method can also be used with backreferences to replace a matched pattern with a new string made up of substrings from the pattern. The example below illustrates this. Code Sample: RegularExpressions/Demos/SsnCleaner.html ssn Cleaner






Code Explanation
The cleanSsn() function is used to "clean up" a social security number. The regular expression contained inRE_SSN, ^(\d{3})[\- ]?(\d{2})[\- ]?(\d{4})$, contains three subexpressions: (\d{3}),(\d{2}), and (\d{4}). Within the replace() method, these subexpressions can be referenced as $1, $2, and $3, respectively.
When the user clicks on the "Clean SSN" button, the cleanSsn() function is called. This function first tests to see that the user-entered value is a valid social security number. If it is, it then cleans it up with the line of code below, which dash-delimits the three substrings matching the subexpressions.
var cleanedSsn = ssn.replace(RE_SSN, "$1-$2-$3");
It then returns the cleaned-up social security number.
Exercise: Cleaning Up Form Entries
Duration: 15 to 25 minutes.
1. Open RegularExpressions/Exercises/PhoneCleaner.html for editing.
2. Where the comment indicates, declare a variable called cleanedPhone and assign it a cleaned-up version of the user-entered phone number. The cleaned up version should fit the following format:(555) 555-1212
3. Test your solution in a browser.
Some phone numbers are given as a combination of numbers and letters (e.g, 877-WEBUCATE). As is the case with 877-WEBUCATE, such numbers often have an extra character just to make the word complete.
1. Add a function called convertPhone() that:
o strips all characters that are not numbers or letters
o converts all letters to numbers
 ABC -> 2
 DEF -> 3
 GHI -> 4
 JKL -> 5
 MNO -> 6
 PRS -> 7
 TUV -> 8
 WXY -> 9
 QZ -> 0
o passes the first 10 characters of the resulting string to the cleanPhone() function
o returns the resulting string
2. Modify the form, so that it calls convertPhone() rather than cleanPhone().
3. Test your solution in a browser.


Hyperlink:-
A “hyperlink” is, most commonly, an underlined word or phrase, or sometimes even a graphic image or icon, which has been tagged with a particular HTML command containing the specific address of another location. Usually, by placing the arrow on the hyperlink and clicking on it, the user will jump quickly or instantly from one location to another location (within the same document, in another document, or somewhere else on the World Wide Web). Occasionally, clicking on a hyperlink will elicit a sound, an image, an animation, or an executable piece of software.
In most internet documents, “unvisited” hyperlinks will be blue in color. After the hyperlink has been activated or “visited,” its color should be changed to purple. On most browsers, these are the two default colors of “unvisited” and “visited” hyperlinks. (On some browsers, the “visited” hyperlink color will be olive.) If you see a hyperlink to a location which your browser previously has visited, its color should be the visited color. (With some web browsers, hyperlinks which make a jump to another location within the same documentare always the visited color, whether those hyperlinks have been activated or not.)
The colors of “unvisited” hyperlinks do not have to be blue, and the colors of “visited” hyperlinks do not have to be purple (or olive). If you will recall, the hyperlink you took to get to this page from the “Ted’s HTML Tutorial” page was sort of a peach color. The next time you see it, its color should have been changed to sort of a dark tan color, because it has been activated to bring you to this page. I chose and implemented those particular colors, thereby overriding the default colors.
In this tutorial we will create two text fields. The first will receive HTML formatting and contain a hyperlink to a webpage. The second text field will contain a hyperlink to an email address.

Creating & Saving Files
Open Flash 9 and select a new Flash file (ActionScript 3.0). Name it HTMLText_Hyperlinks and save it inside the FlasherAS3_PartI folder. In the Document Class box of the Properties panel, type HTMLText and then save the changes.

Open a new ActionScript file, name it HTMLText and then save it inside the Code folder.

You now have twenty-two separate files on your computer:
In the FlasherAS3_PartI folder -
LineAndCurve.fla, Triangles.fla, RectanglesSquare.fla, CircleEllipse.fla, Sprites.fla,MovieClips.fla, Filters.fla, InheritingClasses.fla, FormattedText.fla,LoadExternalText.fla and HTMLText_Hyperlinks.fla.

In the Code subfolder -
LineCurve.as, Triangles.as, RectanglesSquare.as, CircleEllipse.as, Sprites.as,MovieClips.as, Filters.as, InheritingClasses.as, FormattedText.as,LoadExternalText.as and HTMLText.as.
Keep both HTMLText_Hyperlinks.fla and HTMLText.as open as we will be working with both of them simultaneously.


Establishing the Classpath
Return to HTMLText_Hyperlinks.fla and set the Classpath to the Code subfolder inside theFlasherAS3_PartI folder. Save your changes.


Set up AS file to accept code
Return to HTMLText.as and type in the following code:
Line 01: package
Line 02: {
Line 03: public class HTMLText extends Sprite
Line 04: {
Line 05: public function HTMLText()
Line 06: {
Line 07: }
Line 08: }
Line 09: }


Save the changes.


Import appropriate classes
This tutorial will require the Sprite, TextField and TextFieldAutoSize classes so let's import them now.

Place your cursor at the end of line 2 and press Return/Enter.
On line 3 type: import flash.display.Sprite;

Press Return/Enter.

On line 4 type: import flash.text.TextField;

Press Return/Enter.

On line 5 type: import flash.text.TextFieldAutoSize;

Press Return/Enter to add a blank line on line 6.

Place your cursor at the end of line 10 and press Return/Enter.
All of our HTML text code will be placed between the constructor function's opening & closing curly braces.


Save the changes. The set up is done; let's create some HTML text!


Create two text fields
Let's create two text fields (myText and emailLink). First, let's give them each internal scope and place them in the main class instead of the constructor function as we may want to reference them from another custom class (AS file) in the future.

First, create the myText text field. Place your cursor at the end of line 8 and press Return/Enter.
On line 9 type: internal var myText:TextField = new TextField;

Press Return/Enter.

On line 10 type: internal var emailLink:TextField = new TextField;

Press Return/Enter to make line 11 a blank line.

No comments:

Post a Comment