Monday, October 4, 2010 | By: mayurJavascript

Regular Expression(Pattern Matching in Javascript)

The RegExp object is a Core JavaScript Object. RegExp stands for Regular Expression. The RegExp object was based on the PERL implementation of Regular Expressions. PERL is a very capable and powerful scripting language. To put it simply, the RegExp object is used to find a match to the text you want to find. Various "switches" are used to give you options on how to find the text. On your browser, if you select the "find" option from the menu, you type in a string of text you would like to find, then click OK. The browser uses a Regular Expression to find a match to your text within the web page (or whatever application you are working in - the Regular Expression is very widely used, and in many languages).
With the RegExp object, you may not only find a match to your desired text, but also verify user input for things like valid postal and zip codes, telephone numbers, and account numbers. The RegExp object works by first creating a new instance of the Core RegExp object, then assigning a pattern for the object to match, as in the following syntax example.
var name = new RegExp("String of Text"); 
The above syntax example creates a new instance of the RegExp object called name which looks for the string String of Text. While this is the most common method of creating a new RegExp object, there is another more shorthanded form, as follows.
var name = /String of Text/; 
Placing the String of Text between two forward slashes tells JavaScript that the text, the "pattern", must be applied to the RegExp object. This method is called "Direct Assignment".

Defining Your Search Patterns

As mentioned earlier, there is an extensive set of "switches" used to further refine your search. Used properly and with some creativity, it is almost guaranteed that you'll find a specific match to your search string. The pattern matching characters available to JavaScript are given in the list below.
  • \w - Find a match to any alphanumeric character within a word
  • \W - Find a match to any non-word character
  • \s - Find a match to any whitespace character such as a tab character, newline, carriage return (enter), form feed, or vertical tab.
  • \d - Find a match to any numeric digit
  • \D - Find any character that is not a number
  • [ \b ] - Find a match for a backspace.
  • . (period) - Find a match for any character except a newline character.
  • [ ... ] - Match any one character within the square brackets.
  • [ ^... ] - Match any character not within the square brackets.
  • [ x-y ] - Match any character between X and Y.
  • [ ^x-y ] - Match any character not between X and Y
  • { x, y } - Match the previous search string at least X times, not to exceed Y times.
  • { x, } - Match the previous search string at least X times.
  • { x } - Match the previous search string exactly X times.
  • ? - Match the previous search string once or not at all.
  • + - Match the previous search string at least once.
  • * - Match the previous search string any number of times, or not at all
  • | - Match the expression to the left or the right of the | character.
  • ( ... ) - Group everything inside of the parentheses into one sub-pattern.
  • \x - Match the same pattern within the last sub-pattern in group X.
  • ^ - Match the beginning of a string or the beginning of a line, in multi-line search string matches.
  • $ - Match the end of the search string or the end of a line, in multi-line search string matches.
  • \b - Match the position between a word character and a non-word character.
  • \B - Match the position that is not between a word character and a non-word character.
Using the above list of options, it is almost a certainty that you'll find the string you are looking for. But this is not all that JavaScript offers. There is also a list of what are called Literal Characters JavaScript uses to make the search for your string easier, less complicated. That list is as follows.
  • \f - Find a form feed character.
  • \n - Find a new line character.
  • \r - Find a carriage return character.
  • \t - Find a tab character.
  • \v - Find a vertical tab character.
  • \/ - Find a forward slash.
  • \\ - Find a backward slash.
  • \. - Find a period.
  • \* - Find an asterisk.
  • \+ - Find a plus character.
  • \? - Find a question mark.
  • \| - Find a horizontal bar.
  • \( - Find a left parentheses character.
  • \) - Find a right parentheses character.
  • \[ - Find a left square bracket character.
  • \] - Find a right square bracket character.
  • \{ - Find a left curly brace character.
  • \} - Find a right curly brace character.
  • \XXX - Find an ASCII character represented by the octal number \XXX.
  • \xHH - Find an ASCII character represented by the hexadecimal number \xHH.
  • \cX - Find a control character represented by \cX.
You can see that most of the conceivable options have been defined for you. The creators of the JavaScript specifications have been very thorough. But there are two more "switches" that are probably the most commonly used of them all. Those two Pattern Attributes are as follows.
  • \g - This is for a Global Match, and is used to find all possible matches to your search string.
  • \i - This is for a case-insensitive match.

Function in javascript

he JavaScript function is used to contain a set of commands that can be called upon by the HTML coding you specify within the BODY of your document. Any of the many JavaScript commands may be placed within the function, in any amount and in any degree of complexity which you have a use for. As well, you may specify any number of individual functions within your document. While the JavaScript function is not as powerful as those found in languages like C and C++, there is still enough functionality to achieve most actions the modern web page requires.
As with all JavaScript commands, the JavaScript function must be placed within the opening and closing HTML SCRIPT tags, as the following syntax example shows. 

<SCRIPT LANGUAGE="JavaScript">

function functionName(optional parameters) {
   statements;
   }

</SCRIPT> 
You can see that the function is fairly straightforward and is relatively easy to use. Calling a function within your document is as easy as simply stating the functionName within an event handler, as the following syntax example shows.
onClick="functionName(optional parameters) ; return true" 
 
Any event handler that applies to the HTML element it is being used with may call the JavaScript function. The "return true" is used to return a value of true to the script, although some scripts may require a "return false" statement, which returns a value of false to the script. Both are acceptable, and the decisions to use both of them are on a case-by-case basis, according to the demands of the script.
All JavaScript functions use the "call by value" method of using arguments, which basically just makes a copy of the argument. The argument is then used for whatever task you've specified and discarded, if not again required by the script. The original argument is not altered in any way. This "call by value" method is the opposite of the "call by reference" method, which alters the original argument directly without making a copy. When the script is finished execution on the argument, the original has been changed. This can lead to problems at a later time, making the script unduly complicated. Because of this, JavaScript does not use the "call by reference" method.

Returning Values to the JavaScript Function

On occasion, you'll have need to return a value to the function you are working with. To do this, you would use the "return" keyword. The value to be returned to the function is simply stated after the return keyword, anywhere within the function. If no value is specified after the return keyword, a value of "undefined" is returned to the function (this is good to know, as some of your JavaScript machinations may require an initial "undefined" value to be returned). This value returned may then be assigned to a variable for later use or used within an expression, as the following syntax example shows. 

<SCRIPT LANGUAGE="JavaScript">

function functionName(optional parameters) {
   statements;
   return variableName = value;
   }

</SCRIPT> 
 
You can see that the return keyword has been used within the function to create a variable with a value and return it to the function. Any statements within that function can then use the variable, as the variable is of the Local type. The variable is not available to statements or functions outside of the function it was created in. For a more detailed discussion of Local versus Global Variables, see the JavaScript Tutorial on Variables.

The Function as an Object

While most instances of creating a function will involve the function being created as the document loads into the browser, there is another method that only creates the function when it is called upon by other parts of the script. In using this method, the function is considered to be an object, and is treated as such by the script. Examine the below syntax example of creating a function as an object.
var variableName = new Function(argumentOne, argumentTwo, etc.); 
When stating a new instance of the core JavaScript Function object as a variable, the function is treated as an object. The capabilities of the function as an object are less than the other more common method of creating a function. There is no space provided for a statement to be executed on what would be the parameters of the common method of creating a function. There are only a set of arguments available to achieve what it is you set out to do. Use this method when you want to perform simple machinations on a variable that has been created earlier within the script.

Condiional Statetement in Javascript

Conditional Statemnts allow programmers to make their code execute different actions based on different conditions. 

Conditional Statements give the JavaScript code you are writing the ability to make decisions or perform single or multiple tasks. These Conditional statements were borrowed from older, more polished languages like C, C++, and Java. Porting over the functionality of these very capable languages gives JavaScript a very polished set of useful and functionally correct tools which you, the developer, can work with.
A conditional statement uses the operators that were discussed in an earlier chapter. There are three conditionals used within the JavaScript language, which will be discussed in depth in the coming sections. They are as follows.
  • The if and if / else Conditional Statements
  • The else / if Conditional Statement
  • The switch / case Conditional Statement
Each conditional satisfies a slightly different chunk of functionality needed to make very robust and powerful scripts. Each is implemented slightly different, with an eye toward being able to execute what the previous wasn't able to. Working hand in hand this way, the conditionals are able to perform some very impressive programming feats with a minimum of fuss and typing.

The If and If/Else Conditional Statements

The if conditional is used to perform an action "if" the condition is met. Examine the below syntax example to get a feel for how to build a simple if conditional. 

if (expression)
   statement; 
 
The example shows the if keyword followed by an expression within brackets. Within these brackets are the conditions that must be met in order to execute the statement. If the condition is never met, the statement is never executed. Simply put, the expression must evaluate to true in order for the statement to be executed. Within this simple conditional are an infinite number of variations. Basically, you're letting the script make decisions based on the condition, the expression, you supply.
While performing an action if a value of true is returned from the expression is great, you will eventually have a need for something to happen if the expression evaluates to false. Assigning an action to the false output of the expression involves a very simple addition to the if statement given above. The else keyword is used to supply an action to be taken if the expression is false. Examine the syntax example below. 

if (expression) {
   statement If expression is True;
   } else {
   statement If expression is False;
} 
 
 

The If and If/Else Conditional Statements:

 

Notice the addition not only of the else keyword and an additional statement, but also the use of the opening and closing curly braces - { } . The braces are used to encapsulate the true statement and the false statement, as well as divide the entire statement into its "if" and "else" sections. Notice also that the basic JavaScript syntax rules haven't been broken - a semi-colon is present after both the true statement and the false statement.
This is probably the most common of all of the many JavaScript statements. You'll use it often, so get a feel for it now. We'll examine a couple of working examples to help you get a feel for working with the if and if / else statement. 

if (80<100)
   document.write("The expression has evaluated to true!!"); 
 
You can see the basic if statement used very simply here. Notice the "less-than" operator used within the conditional expression - "80<100". This if statement simply states that if 80 is less than 100, the statement is considered to be true. Since 80 is actually less than 100, the document.write statement is written to the screen. If the conditional expression were "101<100" (which is read as "if 101 is less than 100"), then nothing would be written to the screen as the conditional expression would have evaluated to false. Use the if statement if you want something to happen only if the conditional expression evaluates to true.
If you'd like an action to be taken when the conditional expression evaluates to false as well as true, use the else addition to provide an action to be taken when the conditional expression returns a false value, as shown below.
if (101<100) {
   document.write("The expression has evaluated to true!!");
   } else {
   document.write("The expression has evaluated to false!!");
} 
The above if / else statement says that if 101 is less than 100, write the first document.write statement to the screen. If 101 isn't less than 100 the second document.write statement is written to the screen. Since 101 is not less than 100, the conditional expression returns false, and the second document.write statement ("The expression has evaluated to false!!") is written to the screen.
So now that you know the basic structure of the if and if / else statements, we'll delve into another aspect - nesting your if / else statements. This nesting structure is used when you have an initial condition to be met with a true or false value, then you require another set of conditions that you'd like to have tested to acquire your end result. Examine the below syntax example to understand more clearly what is meant by the term "nesting".
if (expression1) {
   statement If expression1 is True;
   } else {
   if (expression2) {
      statement If expression2 is True;
      } else {
      statement If expression2 is False;
   }
}
You can see that the second if / else statement is nested within the "false" area of the first if / else statement. If expression1 evaluates to true, then the first document.write statement of the first if / else statement is written to the screen. If expression1 evaluates to false, then the second if / else statement is evaluated. If expression2 evaluates to true, the first document.write statement of the second if / else statement is written to the screen. If expression2 evaluates to false, then the second document.write statement of the second if / else statement is written to the screen. This somewhat complicated (but very useful) method will be used widely within your future JavaScript coding.
To illustrate further, I'll use the nesting of if / else statements in a couple of working examples, shown below.
if (99<100) {
   document.write("Expression1 has evaluated to true!!");
   } else {
   if (80<100) {
      document.write("Expression2 has evaluated to true!!");
      } else {
      document.write("Expression2 has evaluated to false!!");
   }
} 
 
The example shows the nesting of an if / else statement within another. The first if / else statement shows the less than operator being used to evaluate the weights of two numbers, 99 and 100. Since 99 is indeed less than 100, the conditional expression returns a value of true, and the first document.write statement ("Expression1 has evaluated to true!!") is written to the screen. The false section of the first if / else statement is never consulted, since the conditional expression of the first if / else statement evaluated to true. Examine the below example, which utilizes the decision making ability of the second, nested, if / else statement.
if (101<100) {
   document.write("Expression1 has evaluated to true!!");
   } else {
   if (80<100) {
      document.write("Expression2 has evaluated to true!!");
      } else {
      document.write("Expression2 has evaluated to false!!");
   }
}
Since 101 is less than 100, and the conditional expression of the first if / else statement returns false, the second if / else statement is executed. Since 80 is less than 100, the conditional expression returns a value of true and the first document.write statement of the second if / else statement is executed, writing "Expression2 has evaluated to true!!" to the screen. Simple.

The else / if Conditional Statement

The else / if statement is used to make your script supposedly more readable. I don't concur, preferring to use the if / else structure in all of my scripting. It performs the same actions as does the if / else statement. Examine the syntax example given below.
if (101<100)
   document.write("Expression1 has evaluated to true!!");
   else if (80<100)
      document.write("Expression2 has evaluated to true!!");
   else
      document.write("Expression2 has evaluated to false!!");
You can see that the curly braces required for the if / else statement aren't in attendance. They simply aren't necessary. The above script works the same as does an if / else statement nested within another if / else statement. So much for the else / if conditional statement.

 

The Switch/Case Conditional Statement

The switch / case conditional statement is used to test all of the possible outcomes for the application you are designing. Used with the case keyword, the switch statement can give you the control you require, with many actions possible instead of just the two given with an if / else statement. That is, you are not limited to a true or false answer to decide between only two actions. While the true or false decision is still used at a very basic level, you may have as many outcomes as you have a need for. Examine the syntax example, given below.
switch (expression) { case caseLabel: statement; break; case caseLabel: statement; break; case caseLabel: statement; break; default: statement; } 
 
Notice the colons following the case and caseLabel keywords. This is absolutely required. Don't leave them out. Don't substitute the colons with semi-colons, or your script won't work. And don't forget the colon following the default keyword near the end of the script. The switch statement begins with, of course, the switch keyword. Within the brackets following the switch keyword is the expression, which is used to set the parameter that the rest of the script will use as the data to be used to make a decision. Once this decision is made, the script looks for a match among the various case keywords. Each case keyword has a unique caseLabel associated with it. This is used to define each case statement as a unique and individual entity to your script. Once a case with the matching caseLabel is found, the statement within the case statement is executed. On the end of the switch statement, you'll see that a "default" keyword was used, with a statement of its own given. This default statement is executed when none of the given cases match the expression given in brackets following the switch keyword. Notice also that break; statements were used. The break statements used in this way are required to "break" out of the switch / case structure and go on to further actions. It is required so that the rest of the case options below the selected case (as well as the default actions) aren't executed. To further illustrate the concept, examine the following working example which utilizes the switch / case statement. 

var varOne = 100; switch (varOne) { case 90: document.write("The value of varOne is 90"); break; case 100: document.write("The value of varOne is 100"); break; case 110: document.write("The value of varOne is 110"); break; default: document.write("The value of varOne is unKown"); } 
 
The example shows the declaration of a variable, varOne. varOne contains a number, which is 100. This varOne variable is then used as the expression of the switch statement. Now that the script has the expression with to find a match, the several cases given are searched until a case is found that matches the varOne value, which is 100. Since the second label matches the varOne value given as the expression, the statement within that case statement is executed, which is a document.write statement which writes the words "The value of varOne is 100" to the screen.
It should be noted that you aren't limited to using a variable with a static, unchanging value. You may use a variable that changes dynamically with either user driven or script driven actions associated with it to obtain a changing value.

Array in Javascript

JavaScript is probably the most forgiving language in existence when thought of in terms of data types and their conversions from one data type to another. The JavaScript engine does everything for you. In languages like the many flavors of C, you have to explicitly change the type of data with a statement before it can be used with another data type. This makes for a very tedious job when working with more than one data type, needlessly adding complexity.
JavaScript allows a variable to hold any data type at any time. A situation where this might be useful is when processing user information - the user inputs a string of numbers and you use this input to calculate something-or-other. You would of course use numbers in your calculation. JavaScript will automatically change the data type from the string type the user has input from the web page form to the Number data type so it can be used as part of the calculation. You'll run into many instances where the data type will be changed on the fly according to circumstances. The change of data type, if applicable, is given for each object, method, array, and property within the JavaScript Language Reference.

JavaScript Arrays

An Array is used to hold a piece or many pieces of information. In JavaScript, an array can hold one data type or all types - JavaScript just doesn't care. In languages such as the C flavors, an array can hold only one data type, which can cause headaches in implementation.
The items of an array are numbered starting from the number 0 (zero) and up. There is really no limit on the size of an array. This numbering system is called a Zero Based Index, and will be referred to as such in the coming discussions. The arrays you'll be working with to start with will be of the "shallow" type of array. That is, the array is only one level deep. An array can have an array existing within it - two arrays represented by one name. This type of array is called a MultiDimensional Array, and is considered to be a deep array. An array within JavaScript can be as deep as you have a need for, with the limit being about four levels deep (though I've personally played around with arrays up to twelve levels deep, just for fun). This restriction isn't due to the capabilities of JavaScript, but of the user's computer - you have no idea what the capabilities of the user's machine will be. Working with a very deep array may overwhelm the user's processor. There's a lot of math involved in accessing and working with arrays, though you don't see any of it - it is within the computer's processor and memory.
In the beginning versions of the JavaScript language, there wasn't a real array object to use - the closest was a string of objects with several properties associated with them. In the version 1.1 and up, there is a real array item that works as an array should. Creating your array and working with it is almost as simple as creating and working with variables - it is a simple statement that is easy to understand.

Data Types in Javascript

In JavaScript, every number data type is treated as a floating-point number. A floating-point number is a number that includes a decimal place. For example, the fraction one-half wouldn't be written as .5, but as 0.5. Multiply that 0.5 by 6.1234 (or any number, really), and the decimal (the "point") will have "floated" to a new position within the new number. Hence the term "Floating Point". Because of this floating-point capability, JavaScript is great to use with numbers. Combine this with its loosely typed nature and you get a very easy to use and flexible yet powerful programming language.
Within the Numbers data type, there are a few different variations that must be addressed. Understanding these variations is crucial to your skill in working with them. As with most concepts within JavaScript, they are easy to understand. Along with the different number types are several built in number values that can be used within your scripts. The different types and built in values are as follows.

Integers

An integer is a number that exists without a decimal place. It is a whole number. For example, the number 5 would be an integer, but the number 5.5 would not be due to the existence of a decimal place. An integer may be positive or negative. An integer may be stated as a decimal, octal, or hexadecimal number. The below list explains what is meant by the terms decimal, octal, and hexadecimal.
  • Decimal - A decimal number is any number that exists with a base number of 10. The decimal number is what we (humans) use in every day numbering. It is represented by the numbers (or combinations of) 0 to 9.
  • Hexadecimal - A Hexadecimal number is a number that exists with a base number of 16. The hexadecimal numbering system is widely used within the computing industry because a large value may be stated using a small amount of numbers. It is represented by the numbers 0 to 9 (which represent the decimal numbers 0 to 9) and the letters A to F (which represent the decimal numbers 10 to 15). A hexadecimal number must begin with 0x or 0X when stated within JavaScript. An example of a hexadecimal number stated within JavaScript is 0XFF that represents the decimal number 255.
  • Octal - An Octal number is a number that exists with a base number of 8. The Octal numbering system isn't used within the computer industry as much as the hexadecimal numbering system, but it still finds some applications. It is represented by the numbers 0 to 7 and is stated within JavaScript with a zero following the actual number value. For example, the number 6 in octal must be stated as 06. An example of an octal number stated within JavaScript is 077 that represents the decimal number 63.
You'll get a feel for thinking in these differing number systems with some practice. Don't feel discouraged if you don't catch on quickly. Thinking in a number system other than ten is extremely difficult for a human.

Floating Point Numbers

As explained earlier, a floating-point number is a number that contains a decimal. A Floating-point number may also be expressed through the means of exponential notation. An exponential number may be expressed with the base number followed by an e or E, followed by the power you wish to raise the number to. For example, the number 8 may be expressed as the decimal number 2 raised to the third power as such: 2E3.

Built In Values

There are a number of different built in values you may have a use for. Use these values with the Math object to achieve your desired result. You'll learn more about the Math object later, for now what is important now is that you know they exist. The different built in values are as follows.
  • Math.E - This represents the base of natural logarithms, also called Euler's Constant, which is 2.718281828459045 as a decimal floating point number.
  • Math.LN2 - This represents the value for the natural logarithm of 2, which is 0.6931471805599453 as a decimal floating-point number.
  • Math.LN10 - This represents the value for the natural logarithm of 10, which is 2.302585092994046 as a decimal floating point number.
  • Math.LOG2E - This represents the value for the base 2 of the log of E. E represents Euler's Constant, which is 2.718281828459045 as a decimal floating point number.
  • Math.LOG10E - This represents the value for the base 2 of the log of E. E represents Euler's Constant, which is 2.718281828459045 as a decimal floating point number.
  • Math.PI - This represents the value of PI, which is 3.141592653589793 as a decimal floating point number.
  • Math.SQRT2 - This represents the square root of 2, which is 1.4142135623730951 as a decimal floating-point number.
  • Math.SQRT1_2 - This represents the square root of one half, which is 0.7071067811865476 as a decimal floating- point number.
You may use the above Math functions alone or together within your JavaScript functions. For a more detailed look at each of the above Math object properties, see the JavaScript Language Reference, Object Properties. Special Values
JavaScript has provided five different properties of the Number object to further its capabilities as a math intensive language. They are quite common in the world of mathematics, but not so common in the world of programming. They are as follows.
  • Number.MAX_VALUE - This property is used to return the largest number possible available to JavaScript. This number is 1.7976931348623157e+308.
  • Number.MIN_VALUE - This property is used to return the smallest number possible available to JavaScript. This number is 5e-324, which is five to the negative 324, which is 5 with 324 zeros in front of it, then a decimal point.
  • Number.NaN - This property is used to signify that the value is NaN, which stands for Not A Number. It simply has no other value but NaN. It is equal to no other number, including itself.
  • Number.POSITIVE_INFINITY - The POSITIVE_INFINITY property is returned when a calculation returns a number greater than the largest Positive number available to JavaScript, which is 1.7976931348623157e+308.
  • Number.NEGATIVE_INFINITY - The NEGATIVE_INFINITY property is returned when a calculation returns a negative number greater than the largest negative number available to JavaScript, which is 5e-324.
You may use the above Number functions alone or together within your JavaScript functions. For a more detailed look at each of the above Number object properties, see the JavaScript Language Reference, Object Properties.

Operator In Javascript

An operator in JavaScript is said to be any symbols or group of symbols that performs a very specific function, usually on numbers. Operators are used extensively in JavaScript because of there flexibility - they can be applied not only to numbers, but in special cases can also be applied to strings and other data types. Many of the mathematical functions of operators bring data type conversion into play. The rules for data type conversion are given here and in the JavaScript Language Reference, Operators. There are seven general types of operators, as follows.
  • Arithmetic Operators
  • The String Operator
  • Assignment Operators
  • Logical Operators
  • Comparison Operators
  • The Conditional Operator
  • Bitwise Operators
Each has its own set of rules governing its use and functionality. Each general class has several different operators that you must have an understanding of in order to move on to the higher functions such as loops and conditional statements. Each general type of operator is described in detail in the coming sections. Each operator is also defined in depth and with working examples in the JavaScript Language Reference, Operators.

Arithmetic Operators

An arithmetic operator obviously works with numbers and is used within arithmetic operations. There is a wide variety of operators to work with, from the simple to the advanced. There are many built in mathematical functions to the JavaScript language that are covered in the Numbers Data Type section. Since we've already looked at them, we'll not include them here. There are, however, many different functions available through the Math object. These mathematical methods are listed below.
  • Math.abs() - This method is used to calculate the absolute value of a number.
  • Math.acos() - This method is used to calculate the arc- cosine of a number.
  • Math.asin() - This method is used to calculate the arc-sine of a number.
  • Math.atan() - This method is used to calculate the arc- tangent of a number.
  • Math.atan2() - This method is used to calculate the arctangent of the quotient of its given parameters.
  • Math.ceil() - This method is used to calculate the ceiling of the numbers being worked with.
  • Math.cos() - This method is used to calculate the cosine of a number.
  • Math.exp() - This method is used to calculate the natural exponent of a number.
  • Math.floor() - This method is used to return the floor value of the numbers being worked with.
  • Math.log() - This method is used to calculate the natural logarithm of a number.
  • Math.max() - This method is used to calculate the maximum value for the two parameters passed.
  • Math.min() - This method is used to calculate the minimum value for the two parameters passed.
  • Math.pow() - This method is used to calculate the power of the number passed as the parameter.
  • Math.random() - This method is used to calculate a random number.
  • Math.round() - This method is used to round the number given to the nearest whole number.
  • Math.sin() - This method is used to calculate the sine of a number.
  • Math.sqrt() - This method is used to calculate the square root of a number.
  • Math.tan() - This method is used to calculate the tangent of a number.
Each of the above methods, used with the Math object, give a wide array of functionality to your scripting actions. They may be used alone or in combinations. All of the common arithmetic operators will attempt to convert strings to numbers. If this is not possible, the NaN (Not A Number) data type will be returned. While the above listing is a list of mathematical methods, the following is a list of arithmetic operators, which are different from methods. Each is explored in detail. Again, all of the following are available in an in depth form in the JavaScript Language Reference, Operators.
  • Addition ( + ) - The addition operator is the most commonly used operator. It is obviously used to add two numbers together. When the values on either side of the addition operator are numbers, they are added together. When they are strings, they are concatenated, the second being appended to the end of the first. If a number and a string are being added, the string is converted to a number, then added to the other number. If this conversion is not possible, NaN is returned.
  • Subtraction ( - ) - The subtraction operator is used in subtraction. The subtraction operator subtracts the right number from the left. If either or both of the values are strings, an attempt is made to convert them to numbers. If this is not possible, the value of NaN is returned.
  • Multiplication( * ) - The multiplication operator is used to multiply the left value by the right. When the values on either side of the multiplication operator are numbers, they are multiplied together. When they are strings, they are converted to numbers. If a number and a string are being added, the string is converted to a number, then multiplied by the other number. If this conversion is not possible, NaN is returned.
  • Division ( / ) - The division operator is used to divide the left value by the right value. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
  • Modulus ( % ) - The modulus operator is an interesting one. It is used to return the remainder of the division of the two values given. Neat. As with the division operator, the left value is divided by the right. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
  • Pre-Increment ( ++value ) - The pre-increment operator is a very useful and time saving operator. It is used to increase the number given by one, then return that new, incremented number. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
  • Post-Increment ( value++ ) - The post-increment operator is used to increase the given number by one, but even though the new, decremented number is saved within the variable, it is not returned - the original number is. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
  • Pre-Decrement ( --value ) - The pre-decrement operator is used to decrease the number given by one then return that new, decremented number. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
  • Post-Decrement ( value-- ) - The post-decrement operator is used to decrease the given number by one, but even though the new, decremented number is saved within the variable, it is not returned - the original number is. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.
  • Unary Negation ( - ) - The unary negation operator is used to change the polarity of a number. That is, it converts a positive number to a negative number. You might have noticed that the Unary Negation operator is the same as the subtraction operator. Only its use differs. Use it in front of a positive number to change it to a negative number. Use it in front of a negative number to change it to a positive number. If either or both of the values are a string, an attempt is made to convert the string to a number. If this is not possible, NaN is returned.

A Simple Image/Link Rollover in Javascript

Your web site has been up and running for some time and while you are pleased with the results, you can't help but think that it needs a little bit more "something".
Maybe a tweak or two to make it stand out a little more. Nothing flashy or too complicated.

Maybe you want to do something with the links, like add some pictures or a "rollover effect". Well, maybe not all the links; just one or two. There's a fine line between classy and gaudy.

The problem is: you know nothing about Javascript. To you and a lot of people Javascript looks like ancient Vulcan. And yet there is a solution. Cut and paste comes to mind.
Just head on over to your friendly free Java source, find what you need and cut and paste it into your web page. Sounds simple enough. BUT. As the universe has shown us time and time again...nothing is simple.

Now a couple of hours have passed and you still haven't found what you were looking for. It seems the Java codes you have been looking at, all deal with muliple images and a humoungus amount of code to place in the "head section" and nowhere does it give you instructions as to how to make the rest of the Java code fit into your web page. Forget about where you want to put it.

Believe it or not, there is a small compact Javascript that you can paste into your web page and put it where you want it. And the added bonus is: it's a image link.
You will need three pictures in gif, jpg or bmp: your choice. Two of the three pictures must be the same.
Now here's the Javascript:

<SCRIPT LANGUAGE="JavaScript">
Step one: Paste this code into the Head section of your HTML of your document.
<Head>
<script>
{!-- Hide Script function move_in(img_name,img_src) { document[img_name].src=img_src; }
function move_out(img_name,img_src) { document[img_name].src=img_src; }
//End Hide Script--}
</script>
</head?>

Step two: Paste this code into the Body of your Html document
<body>
{a href="anylink.html
OnMouseOver="move_in('image1','image_on.gif')"
OnMouseOut="move_out('image1','image_out.gif')"}
<img src="image_out.gif">
<alt="Move your mouse over here!" name="image1">

< /a>
</body>
</html>

Now look down under the "body" tag and you will see: OnMouseOver="move_in('image1','image_on.gif')". Image_on.gif is the picture you want displayed. Image_out is what will be seen when you roll your mouse over the image.
So far that's two images. The final image will go into the last peice of code which is "image_out.gif". This should be your copy image. You can also change the information in the "alt" tag to whatever you like. Place any link you want in the "link" tag.
This little peice of Javascript code makes a great preview picture link for whatever site you want to link it to. Have fun with this. Experiment with different images or just use text and an image. It's very versatile. I think it works best in tables and should be most effective in getting some attention for you web pages

Web Development & Design Techniques for Websites

In this high tech world we have seen extensive growth of internet, and with the growth of internet we have seen high growth rate of business through internet. With some statistics available with us we have seen that almost 60%-70% businesses are running over internet. Many people would think that how businesses can would run through internet? The answer to this question is that businesses have website which are online on the World Wide Web (www), through which they sell their services and products. Website consists of web development & web designing. Detail descriptions of these are mentioned below:

Web Development: It is very obvious that internet is useless without websites as they would be nothing to view without a website. People those who are familiar with internet and use internet they must know something about websites or they must have atleast visited a website. A website contains many things or components that comprise in website like company logo, images, text, contents and many other things depending on the nature of the website.
They are points that should be considered while developing a website:

A) Reasonable use of Flash/Images: These days' images & flash have become an important part of websites to get more attraction of users of the internet. But while designing & developing websites we should keep in mind that we use reasonable amount of flash and images as they are not good for search engines.

B) Great Content: Content is a very vital for the website and for the search engines as well. The crawler reads the text of the website and based on that provides desired rating and other benefits to the website. You should keep in mind that the content is not irrelevant as it may make your visitor to leave the website and switch over to other website. It would be better that if you update your content on regular basis.

C) Importance of User Friendly Website : Make sure that your visitor has easy navigation to view your website and also make sure that your website is easy to understand and the user gets what he/she is searching for. The website should be user friendly otherwise you will loose a potential user.

D) Proper use of Alt & Title Tags: If you have images in your website than label those appropriately by using keywords or image related words. Use alt tags and title tags which are even best according to SEO point of view.

E) Use Meta Tags: Website(s) contains many pages that are called inner page or web pages. Make sure that you mention appropriate title and description for al the pages of your website. These are called "META TAGS", they include title, description and keywords. Give a proper title that can best describe your web page and within 250 characters (approx.) mention a description/summary of the page, also mention some related keywords that can help search engine to find your web page related to the keywords.
The above are the basic considerations that should be given while web development and web designing. Creating websites are easy and you can design them at your own using some provided web templates or get it design from some famous and well known web development UK companies. Although you may find many other companies that can help you design a website in any part of the world and even near to you.
Sunday, October 3, 2010 | By: mayurJavascript

Excitement of Java

Several years ago, Java was introduced. It was slow. Now, computers have beefed up, the internet is a lot faster, and Java is a serious language. It can lower costs, and REALLY get people talking about your website! I'll cover:

1) WHAT is Java, and how can it help me? 2) WHY Java NOW? 3) WHY is Java the next BIG THING? 4) CONCLUSIONS

. . .

1) WHAT is Java, and how can it help me?

. . .

Java is basically a programming language that can be integrated into browsers, and add spice to a website. One beautiful thing is its 'reusability', and 'ease of use'.

For example -- I will use the classic 'Lake' example, where you have a picture of a mountain on top of a lake, and the water ripples.

Before Java, you needed expensive graphics software and several hours to make it ripple. Using a Java applet, all you have to do is include something like:

<applet code=Lake.class> <param name="image" value="lake.jpg" </applet>

in your webpage, and now you now have a picture of a lake that ripples! To change the image, simply change the name of the file (the "lake.jpg")!

So -- Java makes it VERY easy to add and change functionality in your website.

. . .

2) WHY Java NOW?

. . .

About five years ago, Java was introduced, and ran it really slowly. The main browsers (Netscape & Internet Explorer) that supported Java were 'brand' new. And, the computers they ran on were slow. If you had a 'top of the line computer', it meant you had a Pentium-133 machine (and friends were usually jealous that you could afford such a 'fine' piece of hardware). Most people were just learning what E-Mail was.

All that has changed.

Microsoft & Netscape have re-written their browsers' JVM (java virtual machine), and optimized it to make Java lightning fast.

Pentium-III 550 MHz machines cost less than the Pentium-133 models did. Plus, they are more than three times faster, because of faster graphics accelerator cards, increased RAM and so forth. And most people have one of these newer machines, because of the low cost (or special 'package' deals that ISP's made with computer makers for 'free' or 'low cost' computers)

So, now Java is fast, and can be easily used, with low development costs.

. . .

3) WHY is Java the next BIG THING?

. . .

A) NO PLUGINS ARE REQUIRED! Most internet users find it EXCEPTIONALLY annoying to have to wait 3 or 4 minutes to download a special plug-in to hear audio, another special plug-in to see 3D images, and so forth. JAVA DOES NOT REQUIRE PLUGINS! Practically 99% of all internet browsers ALREADY SUPPORT JDK 1.0.2, (which is the 'main' version of Java in use today).

B) SPEED Complex mathematical calculations (for 2D & 3D games, visual special fx, data processing, etc) are fast because of fast computers and optimized browsers.

C) RE-USABILITY! Say you bought a program that simply did special transition FX. You decide to use for banner advertisements, and it works as follows:

<applet code=SpecialFX_Transition_Program.class> <param name="image1" value="banner_1.jpg"> <param name="image2" value="banner_2.jpg"> <param name="special_effect" value="Pixel Wipe"> <param name="special_effect" value="Star Burst"> </applet>

So, YOU SAVE TIME AND MONEY, because all your development team has to do is spend five minutes deciding which banner advertisements to use. Now, say you have a big corporate presentation to make. YOU CAN RE-USE THAT PROGRAM! Simply replace each image with the corporate slide image! For example,

<applet code=SpecialFX_Transition_Program.class> <param name="image1" value="corporate_presentation_slide_1.jpg"> <param name="image1" value="corporate_presentation_slide_2.jpg"> <param name="special_effect" value="Pixel Wipe"> <param name="special_effect" value="Star Burst"> </applet>
And that is IT!

D) INCREDIBLY SMALL APPLET SIZE! Most 'sophisticated' applets are less than 50K. Popular and useful tools such as Macromedia Flash create animations that are usually at least 100K for simple ones, and upwards of 500K for high profile/professional sites. So think about it -- if a individual has no problem waiting for a 500K for a Macromedia Flash animation, they are certainly not going to have a problem with a small, 50K Java applet. Most Java applets are even smaller than this!

. . .

4) CONCLUSIONS

. . .

1) You customers are happy (NO PLUGINS required!) 2) Runs FAST! 3) YOU save time & money, because of RE-USABILITY! 4) Customers will talk about how 'GREAT' your site it is, because of all amazing functionality!

So, where do you want to use Java today?

Use External Js File

When you have lots of JavaScript functions and you plan to use them on many web pages, it is always advisable to keep them in a separate file, and then include that file on every page where those functions are required. This way, you can better organize them, you don't have to copy/paste the code again and again (imagine if it runs to 100 or more lines!!), and you'll be forced to write more generalized code for better integration and scalability.

Besides, enclosing the common JavaScript routines in external files keeps your web pages uncluttered and search engine spiders and crawlers are able to reach the important content easily. They don't have to shuffle through tens of lines of scripts.

It's very simple. Use any text editor of your liking (if you hand-code your HTML, you can use the same editor that you use for your HTML editing). Write the required code, and save the file with .js (dot js) extension.

I'm going to give you a small example.

Suppose your JavaScript file is "myjfuncs.js".

and it has a function to return the bigger number of the two supplied as parameters (you can simply start with the function, no need to write <script> or some other stuff):

function bigger(num1, num2) { var holdbig; if (num1<num2) { holdbig=num2; } else if(num1>num2) { holdbig=num1; } else { holdbig=num1; } return holdbig; }

In a similar manner, we can have

function smaller(num1, num2) {

}


When we want to use this precious file full of JavaScript functions, we use this line:

<script language="JavaScript" type="text/javascript" src="myjfuncs.js"> </script>

So when we use one of its functions in a JavaScript:

<script language="javascript">

var n1=90; var n2=7; alert ("The bigger number is: " + bigger(n1, n2));

</script>


In this way, we can use all the complex functions contained in the myjfuncs.js file.

Javascrpt Tips2

JavaScript can be one of the most useful additions to any web page. It comes bundled with Microsoft Internet Explorer and Netscape Navigator and it allows us to perform field validations, mouse-overs images, open popup windows, and a slew of other things.

In this article I will show you how to:

- Display the browser name and version number - Change the text in the status bar of the browser - Use an input box to get text from the user - Use a message box to display text to the user - Change the title of the browser window

Before that, however, we need to know how to setup our web page so that it can run the JavaScript. JavaScript code is inserted between opening and closing script tags: <script> and </script>, like this:

<script language="JavaScript">

// JavaScript code goes here

</script>


These script tags can be placed anywhere on the page, however it's common practice to place them between the <head> and </head> tags. A basic HTML page that contains some JavaScript looks like this:

<html> <head> <title> My Test Page < itle> <script language="JavaScript">

function testfunc() { var x = 1; }

</script> </head> <body> <h1>Hello</h1> </body> </html>


For the examples in this article, you should use the basic document format I have just shown you, inserting the JavaScript code between the <script> and </script> tags. When you load the page in your browser, the JavaScript code will be executed automatically.

----------------------------------------------- Displaying the browsers name and version number -----------------------------------------------

The "navigator" object in JavaScript contains the details of the users browser, including its name and version number. We can display them in our browser using the document.write function:

document.write("Your browser is: " + navigator.appName); document.write("
Its version is: " + navigator.appVersion);

I run Windows 2000 and Internet Explorer version 6, so the output from the code above looks like this in my browser window:

Your browser is: Microsoft Internet Explorer Its version is: 4.0 (compatible; MSIE 6.0b; Windows NT 5.0)

----------------------------------------------- Changing the text in the status bar of the browser -----------------------------------------------

To change the text in the status bar of a browser window, we just change the "status" member of the "window" object, which represents our entire browser window:

window.status = "This is some text";

----------------------------------------------- Using an input box to get text from the user -----------------------------------------------

Just like in traditional windows applications, we can use an input box to get some text input from the user. The "prompt" function is all we need:

var name = prompt("What is your name?"); document.write("Hello " + name);

The prompt function accepts just one argument (the title of the input box), and returns the value entered into the text box. In the example above, we get the users name and store it in the "name" variable. We then use the "document.write" function to output their name into the browser window.

----------------------------------------------- Using a message box to display text to the user -----------------------------------------------

We can display a message box containing an OK button. These are great when you want to let the user know what is happening during their time on a particular page. We can use a message box to display the "name" variable from our previous example:

var name = prompt("What is your name?"); alert("Your name is: " + name);

The "alert" function takes one argument, which is the text to display inside of the message box.

----------------------------------------------- Changing the title of the browser window -----------------------------------------------

To change the title of our web browser's window, we simply modify the "document.title" variable, like this:

document.title = "My new title";

One bad thing about the "document.title" variable is that we can only manipulate it in Microsoft Internet Explorer. Netscape's implementation of JavaScript doesn't allow us to modify it.

----------------------------------------------- In Closing -----------------------------------------------

As you can see from the examples in this article, JavaScript is a powerful scripting language that we can use to enhance our visitors experience with our site. You shouldn't use JavaScript too much, however, because in some cases it can annoy your visitors and send them packing before your site even loads!

Javascrpt Tips

This time we'll make a form that collects information about the visitor at your site. You must have filled-in copious registration forms or survey forms where you had to enter your name, your email, your address, etc. Sometimes users, intentionally or unintentionally, enter wrong information that can either spoil your database scheme or give you lots of useless data and hence, waste your precious server space.

To avoid such problems, as much as it can be managed, we programmatically try to make sure, that data is entered in an orderly fashion, and no unusable fields are entered. Checking individual fields of the form does this.

We'll see a form here with three fields: Name, Phone and Email. In this form, no field should be left blank, there should be no numbers in the Name field [1,2,3,4,.], and in the Email field, no email should be without the "@" sign. We can carry out more complex validations, but at the moment, these three should suffice.

/// Remove the extra dots while testing. They have been just inserted so that some email programs don't freak out at the presence of a JavaScript in the email.

<..script language="JavaScript1.2"> function CheckName(HoldName) { NoNumThere='true'; for(i=0; i<HoldName.length; i++) { for(j=0; j<10; j++) { if(HoldName.charAt(i)==j.toString()) { NoNumThere='false'; break; } } if(NoNumThere=='false') { break; } } return NoNumThere; } function CheckMail(HoldMail) { IsValid='true'; if(HoldMail.indexOf("@")<=0) { IsValid='false'; } return IsValid; } function checkfields() { var AllFilled='true'; for(i=0; i<3; i++) { if(visitor.elements[i].value.length==0) { alert("The field [" + visitor.elements[i].name + "] can not be left blank."); AllFilled='false'; visitor.elements[i].focus; return; } } if(AllFilled=='true') { var NameValid=true; var EmailValid=true; NameValid=CheckName(visitor.vname.value); EmailValid=CheckMail(visitor.vemail.value); if(NameValid=='false') { alert("Sorry, your name can not contain numbers."); visitor.vname.focus; } if(EmailValid=='false') { alert("Sorry, this does not seem like a valid email address."); } } if(NameValid=='true' & EmailValid=='true') { alert("RIGHTO!!!"); } } </script> <body> <form name="visitor"> Enter your name: <input name="vname" type="Text">
Enter you phone: <input name="vphone" type="Text">
Enter your email: <input name="vemail" type="Text">
<input type="Button" name="submit" value="Submit" onclick="checkfields();"> <input type="Reset" name="reset" value="Reset"> </form>

</body> </html>

Copy and paste the code as it is, and save the entire content as a new HTML page. Then load it on to your browser. Unless you see the result, it'll be difficult to follow the script if you do not have prior programming background. The first condition is, none of the fields can be submitted blank. Click on the submit button without entering anything and observe the reaction.

Here, we are making ample use of the recently learnt for(){.} loop. Then we have used function too, to carry out certain validations. Our main function, checkfields(), is associated with the OnClick attribute of the "Submit" button, that is, when you click on the "Submit" button, this function gets triggered.

Some new terms in today's script are: true, false, charAt(), toString(), break, indexOf(), string.length, and orm.elements[ ].

A quick explanation to make things easier:

If at 10:30 pm, I say, "It is night", then

var fact='true'

and if I say at 10:30 pm that "It's afternoon", then

var fact='false'

Which explains the use of true and false, which are also called Boolean operators, which means, a Boolean variable can either be true or false, but NEVER both.

Until we learn about arrays, every character in a string has an index position. For instance, if we have

var city="Delhi"

then city.charAt(0)="D", city.charAt(1)="e", city.charAt(2)="l"...city.charAt(4)="i".

toString(), converts another data type to a string data-type. For example,

var num1=31 var num2=21 var char1=num1.toString() var char2=num2.toString()

So,

num1+num2=52 and char1+char2=3221

In the second case, instead of being added, the variables are being concatenated, which indicates that they are strings, not numbers. We'll see its application later.

break, true to its name, breaks something. In this case, it breaks the loop in which it occurs, and takes the execution of the program to the line immediately after the loop, without meeting the condition required to complete the loop.

indexOf() tells us about the position of a particular character in a string. Look its use in the following code:

var city="Delhi"

Referring to this code, city.indexOf("e") should give us a value 1 and city.indexOf("h") should give us a value 3. city.indexOf("z") should give us a value less than zero, indicating that it does not belong to the given string.

String.length gives us the length of the string, for instance, if city="Delhi", then city.length would give us 5.

Again, elements[ ] is an array, and we haven't dealt with them yet, so we leave the rest of the explanation to the next section.