JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
math.SQRT2
The SQRT2
property of the Math
object returns the value of the square root of 2. This is approximately equal to 1.414.
Listing 7.256 shows how the SQRT2
property is used. The function, doMath
, returns the square root of 2 to the text box on the page.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Function returns the square root of 2.
function doMath(){
var result = Math.SQRT2;
document.form1.answer.value = result;
}
// -->
</script>
<form name=“form1”>
The square root of 2 is:
<input type=“text” name=“answer” size=“20”>
<input type=“button” value=“Calculate” onClick='doMath()'>
<br>
</form>
</body>
</html>
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
math.tan (num)
The tan()
method of the Math
object is to calculate the tangent of a number. It returns a value representing the tangent of an angle.
Listing 7.257 shows how the tan()
method is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Function returns the tangent of input number.
function doMath(){
var inputNum1=document.form1.input1.value;
var result = Math.tan(inputNum1);
document.form1.answer.value = result;
}
// -->
</script>
<form name=“form1”>
This example calculates the tangent of the entered number.
<br><br>
Enter Number:
<input type=“text” name=“input1” size=“10”>
<input type=“button” value=“Calculate” onClick='doMath()'>
<br>
The tangent is:
<input type=“text” name=“answer” size=“20”>
</form>
</body>
</html>
JavaScript 1.3+
Nav4.06+
math.toSource()
The toSource()
method of the Math
object is used to create a copy of the object. It returns a string representation of an object, which can be passed to the eval()
method to create a copy of the object.
Listing 7.258 shows how the toSource()
method is used to make a copy of the Math
object.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Function makes copy of math object.
function copy(){
var result = Math.toSource(Math.E);
document.form1.answer.value = result;
}
// -->
</script>
<form name=“form1”>
Click on the button to create a copy of a Math object.
<br><br>
<input type=“button” value=“Copy” onClick='copy()'>
<br>
The result of toSource is:
<input type=“text” name=“answer” size=“20”>
</form>
</body>
</html>
JavaScript 1.0+, JScript 3.0+
Nav2+, NES2+, IE4+
math.toString()
The toString()
method of the Math
object returns a string value representing the object.
Listing 7.259 shows how the toString()
method is used to get a string value representing the Math
object.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Function returns string representation of math object.
function copy(){
var result = Math.toString(Math.sqrt(45));
document.form1.answer.value = result;
}
// -->
</script>
<form name=“form1”>
<input type=“button” value="Get String" onClick='copy()'>
<br>
The result of toString is:
<input type=“text” name=“answer” size=“20”>
</form>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+
math.unwatch (prop)
The unwatch()
method of the Math
object is used to turn off the watch on a particular property specified by prop. It is inherited from the Object
object; however it cannot be used because math properties are read-only.
All math properties are read-only; therefore, no example can be provided.
JavaScript 1.2+
Nav4+, NES3+
math.watch( prop, handler )
The watch()
method of the Math
object will watch for an assignment to a specific property, prop
. When an assignment is made, a specified handler
will be called to perform a user-defined function. It is inherited from the Object
object; however, it cannot be used because math properties are read-only.
Math properties are read-only; therefore, no example is provided.
JavaScript 1.3+, JScript 1.0+
Nav4.06+, IE3+
NaN
The NaN
object represents an object that is not equal to any number, including itself. NaN
stands for Not a Number.
Listing 7.260 shows how the NaN
object is used within a comparison.
<script type=“text/javascript” language=“JavaScript”>
<!--
// Check to see if “a” is a number or not.
if (“a” != NaN){
document.write("This is not a number");
}
// -->
</script>
JavaScript 1.2+
Nav4+, NES3+
Reserved Keyword
The native
keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.
This keyword has not been implemented, therefore no example is provided.
JavaScript 1.1+
Nav3+, NES2+, Opera3+
netscape
The netscape
object allows you to access any class within the package netscape.*
. It is shorter and works the same way as using the packages.netscape
property.
Listing 7.261 shows how the netscape
property can be used to determine whether the current browser supports the netscape
package.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Check to see if the netscape package exists.
if (netscape){
document.write ("This browser has the netscape package");
}
else{
document.write ("This browser does not have the netscape package");
}
// -->
</script>
</body>
</html>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
new
The new
operator is used to create a new object.
Listing 7.262 shows how new
is used to create a new Array
object.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Creates a new array object with the name myArray.
var myArray = new Array();
// -->
</script>
</body>
</html>
JavaScript 1.2+, JScript 3.0+, ECMAScript 1.0+
Nav4+, NES3+, IE4+
Reserved Keyword
The null
keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.2+, ECMAScript 1.0+
Nav4+, NES3+, IE5+
Number (obj)
The Number()
method takes an object, obj
, as input and converts it to a number. If the object is a string that is not a well-formed numeric literal, NaN
is returned.
Listing 7.263 shows an example of the Number()
method. A new Date
object is created and converted to a number.
<html>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Create a Date object.
var myStr = new Date();
// Convert the Date to a Number object and display.
document.write("The Number is: " + Number(myStr));
// -->
</script>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+
Nav3+, NES2+, IE3+, Opera3+
var variable = new Number(value)
The Number()
object represents numeric value types. You can create a Number()
object by specifying a value in the parameter for the number constructor. Table 7.40 shows the different methods and properties of the Number()
object.
Listing 7.264 shows how a new Number
object is created.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Creates a new number object.
var aNum = new Number(3);
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE4+
Number.constructor
The constructor
property of the Number
object specifies the function that creates the object.
Listing 7.265 shows an example of the constructor
property.
<html>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Create a new number object using the constructor property.
num = new Number(3)
if(num.constructor == Number){
document.write("Object is created");
}
// -->
</script>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Number.MAX_VALUE
The MAX_VALUE
property of the Number
object is used to get the maximum representable value for a number. This is approximately: 1.79E+308.
Listing 7.266 shows how the MAX_VALUE
property is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Checks to see if the number is a MAX_VALUE.
if((9999*9999) != Number.MAX_VALUE){
document.write("The number is not greater than the maximum value");
}
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Number.MIN_VALUE
The MIN_VALUE
property of the Number
object is used to get the minimum possible numeric value known to JavaScript. This is approximately: 2.22E–308.
Listing 7.267 shows how the MIN_VALUE
property is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Checks to see if the number is equal to the MIN_VALUE.
if((0.00000002) != Number.MIN_VALUE){
document.write("The number is not the minimum value");
}
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Number.NaN
The NaN
property of the Number
object represents a value that is not equal to any numeric value.
Listing 7.268 shows how to use the NaN
property. An integer constant, 123
, is compared to the NaN
constant to see whether it is a numeric value.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Checks to see if 123 is a number or not.
if(123 == Number.NaN){
document.write("This is not a number");
}
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Number.NEGATIVE_INFINITY
The NEGATIVE_INFINITY
property of the Number
object represents a negative infinity number. It is returned when a calculation returns a negative number greater than the largest negative number in JavaScript.
Listing 7.269 shows how the NEGATIVE_INFINITY
property is used. The sqrt()
method is used on a number and the result is compared to NEGATIVE_INFINITY
.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Performs a square root calculation to obtain a negative result
// and then checks against the NEGATIVE_INFINITY value.
if((Math.sqrt(-2)) != Number.NEGATIVE_INFINITY_){
document.write("This is not equal to NEGATIVE_INFINITY");
}
else{
document.write("This is equal to NEGATIVE_INFINITY");
}
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Number.POSITIVE_INFINITY
The POSITIVE_INFINITY
property of the Number
object represents a positive infinity number. It is returned when a calculation returns a positive number greater than the largest number in JavaScript.
Listing 7.270 shows how the POSITIVE_INFINITY
property is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Performs some math computation and then checks the
// result against the POSITIVE_INFINITY value.
if((Math.exp(999)) != Number.POSITIVE_INFINITY_){
document.write("This is less than POSITIVE INFINITY");
}
else{
document.write("This is greater than POSITIVE_INFINITY");
}
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Number.prototype.property
Number.prototype.method
The prototype
property of the Number
object allows you to add properties or methods to all instances of this class.
Listing 7.271 shows how the prototype
property is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Creates a new Number property myProp.
var myProp = new Number();
// Sample function multiplies number by 3.
function triple(num){
var result;
result = (num * 3);
return result;
}
// Add the prototype property to the number object.
Number.prototype.calc3 = triple;
document.write("Example demonstrates the prototype property for the number
object." + "<br><br>");
document.write("150 tripled is: " + myProp.calc3(150) + "<br>");
// -->
</script>
</body>
</html>
JavaScript 1.3+, ECMAScript 3E+
Nav6+, IE5.5+
number.toExponential()
The toExponential()
method of the Number
object is used to get an exponential representation of the Number
object.
Listing 7.272 shows how the toExponential()
method is used.
<script type=“text/javascript” language=“JavaScript”>
<!--
var abc = 51000;
// Convert the number to Exponential form and display.
document.write("The variable in exponential form is: " + abc.toExponential() );
// -->
</script>
JavaScript 1.4+, ECMAScript 3E+
Nav6+, IE5.5+
number.toFixed(num)
The toFixed()
method of the Number
object is used to get a fixed-point string representation of the Number
object. The num
parameter represents the number of digits after the decimal point.
Listing 7.273 shows how the toFixed()
method is used to get the fixed form of the standard Number object.
<script type=“text/javascript” language=“JavaScript”>
<!--
var standard = 888000.4325;
// Convert the number to a fixed form and display.
document.write("Fixed Form is: " + standard.toFixed(0) );
// -->
</script>
JavaScript 1.4+, ECMAScript 3E+, JScript 1.0+
Nav6+, IE5.5+, Opera5+
number.toLocaleString()
The toLocaleString()
method of the Number
object is used to get a string value that represents the Number
object. The value will be formatted according to the conventions of the host environment’s current locale.
Listing 7.274 shows how the toLocaleString()
method is used to display the string value of myNum
.
<script type=“text/javascript” language=“JavaScript”>
<!--
var myNum = 123456789;
// Get the string value and display.
document.write("The Locale String is: " + myNum.toLocaleString() );
// -->
</script>
JavaScript 1.4+, ECMAScript 3E+
Nav6+, IE5.5+
number.toPrecision(num)
The toPrecision()
method of the Number
object returns a string representation of the number in the format of one digit before the significand’s decimal point and num-1 digits after the diginificand’s decimal point.
Listing 7.275 shows how the toPrecision()
method is used.
<script type=“text/javascript” language=“JavaScript”>
<!--
var myNum = 123456789.4444;
// Return the result of the toPrecision() method on myNum.
document.write("The Precision String is: " + myNum.toPrecision(2) );
// -->
</script>
JavaScript 1.3+, ECMAScript 1E+
Nav4.06+
number.toSource()
The toSource()
method of the Number
object is used to get a string representation of the Number
object.
Listing 7.276 shows how the toSource()
method is used.
<script type=“text/javascript” language=“JavaScript”>
<!--
// Creates a new number object and then gets the string
// representation of that object.
var aNum = Number(21);
document.write(aNum.toSource());
// -->
</script>
JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+
Nav3+, NES2+, IE3+, Opera3+
number.toString()
The toString()
method of the Number
object is used to get a string representation of the Number
object.
Listing 7.277 shows how the toString()
method is used.
<script type=“text/javascript” language=“JavaScript”>
<!--
var aNum = Number(21);
// Return the string representation of aNum.
document.write("The string value for 21 is: " + "<b>"
+ aNum.toString() + "</b>");
// -->
</script>
JavaScript 1.1+, JScript 3.0+
Nav3+, NES2+, IE4+
number.unwatch(prop)
The unwatch()
method of the Number
object will remove a watch point on a property set by the watch()
method.
Listing 7.278 shows an example for the unwatch()
method.
<html>
<script type=“text/javascript” language=“JavaScript”>
<!--
function alertme(id,oldValue,newValue)
{
document.writeln("myNum." + id + " changed from " + oldValue
+ " to " + newValue + "<br>")
return newValue;
}
// Create a new Number object.
var myNum = new Number(10);
// Create a new property p.
Number.prototype.p = 1;
myNum.watch(“p”,alertme);
myNum.p = 2;
// Remove the watchpoint.
myNum.unwatch(“p”);
myNum.p = 3;
myNum.p = 4;
// Set the watchpoint.
myNum.watch(“p”,alertme);
myNum.p = 5;
// -->
</script>
</html>
JavaScript 1.1+, JScript 2.0+
Nav3+, NES2+, IE4+
number.valueOf()
The valueOf()
method of the Number
object is used to get the primitive value of a Number
object as a number data type.
Listing 7.279 shows an example for the valueOf()
method. A Number
object is created and set to myNum
. The document then outputs the result of performing a valueOf
function on the number.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Create a new number object.
myNum = new Number(24)
// Output the valueOf result.
document.write("The value of myNum is: " + myNum.valueOf());
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+
number.watch(prop, handler)
The watch()
method of the Number object will watch for an assignment to a specific property, prop
. When an assignment is made, a specified handler
will be called to perform a user-defined operation.
Listing 7.280 shows an example for the watch()
method.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Function to alert user that p has changed.
function alertme(id,oldValue,newValue)
{
document.writeln("myNum." + id + " changed from " + oldValue
+ " to " + newValue + "<br>")
return newValue;
}
var myNum= new Number(10);
// Create a new property p.
Number.prototype.p = 1;
// Set the watchpoint on p.
myNum.watch(“p”,alertme);
myNum.p = 15;
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript1.0+
Nav3+, NES2+, IE3+, Opera3+
var variable = new Object(string)
The Object()
object is a primitive data type from which all JavaScript objects are derived. Table 7.41 shows the different properties and methods of the Object()
object.
Listing 7.281 shows how the Object
object is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Create an Object.
var myObj = new Object(foo);
document.write(Object foo created);
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+ Nav3+, NES2+, IE4+
object.constructor
The constructor
property of the Object
object specifies the function that creates the object.
Listing 7.282 shows an example of the constructor
property.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Create a new number object using the constructor property.
num = new Number(3)
if(num.constructor == Number){
document.write("Object is created");
}
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES2+, IE4+
object.eval (string)
The eval()
method of the Object
object evaluates a string
of JavaScript code in reference to this object. Note: In version 1.4 and later, the eval()
method is deprecated and can no longer be called directly for the Object
object. To use eval()
in versions 1.4 and 1.5, you must use the top-level eval()
function.
Listing 7.283 shows how the eval()
method is used. Two variables are declared and set. A statement multiplying the two variables together is passed to the eval()
method to be evaluated.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
var x = 9;
var y = 8;
// Display the result of x*y.
document.write("The result of x * y is: " + eval(x * y));
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE4+
object.prototype.property
object.prototype.method
The prototype
property of the Object
object allows the addition of properties or methods to the Object
class.
Listing 7.284 shows how the prototype
property is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
Object.prototype.newProperty = 2;
// Display the value of the newProperty.
document.write(document.object.newProperty.value);
// -->
</script>
</body>
</html>
JavaScript 1.3+
Nav4.06+
object.toSource()
The toSource()
method is used to get a string representation of the object.
Listing 7.285 shows how the toSource()
is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Creates a new number object and then gets the string
// representation of that object.
var aNum = Number(21);
document.write(aNum.toSource());
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE4+, Opera3+
object.toString()
The toString()
method is used to get a string representation of the Number
object.
Listing 7.286 shows how the toString()
method is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Creates a number object.
var aNum = Number(21);
// Converts the number object to a string and outputs to document.
document.write(aNum.toString());
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+
object.unwatch (prop)
The unwatch()
method of the Object
object allows you to remove a watchpoint set on a property with the watch()
method. This method takes the property,prop, as a parameter.
Listing 7.287 shows how the unwatch()
object is used. A temporary variable, tmp
, is created and initialized. It is then set to be watched by invoking the watch()
method. If any changes occur to the tmp
variable, the inform
function is called. After a change is made to the variable, unwatch()
is called to turn off watch operations on the variable. After watch operations are disabled, the variable can be changed without notification.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Function informs the user when the tmp variable is changed.
function inform(){
document.write("Tmp variable changed from 1 to 3");
}
// Declare a tmp variable.
var tmp = 1;
// Watch the tmp variable for any changes.
watch(“tmp”,inform);
tmp=3;
// Turn off watch on the tmp variable.
unwatch(“tmp”);
tmp=7;
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES2+, IE4+, Opera3+
object.valueOf()
The valueOf()
method for the Object
object is used to obtain the value of the specified object.
Listing 7.288 shows how the valueOf()
method is used.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Declare an age variable which contains a Number object.
var age = Number(30);
// Calculate the valueOf the variable and output to the document.
document.write(age.valueOf());
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+
object.watch(prop, function)
The watch()
method of the Object
object is used to watch for the event in which a property gets assigned a value. When the assignment is made, a user-defined function is executed. The method itself takes the property to watch, prop
, and the function to call, func
, when the event occurs.
Listing 7.289 shows how the watch()
method is used.
<html>
<body>
<title>Example of the watch method</title>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Function informs the user when the tmp variable is changed.
function inform(){
document.write("Tmp variable changed from 1 to 3");
}
// Declare a tmp variable and initialize.
var tmp = 1;
// Turn on watch operations on the variable.If the tmp
// variable is changed, then the inform function is run.
watch(“tmp”,inform);
// Change the tmp variable.
tmp=3;
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+
Reserved Keyword
The package
keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.1+
Nav3+, NES2+
Packages.packagename
The Packages
object is a built-in object that provides access to various Java packages within the browser. Each property of the Packages
object refers to a JavaPackage
object containing references to specific classes. Table 7.42 shows the default packages included in the Packages
object.
Listing 7.290 shows how the Packages
object is used. The user is provided with an input text box. When something is entered in the input box and the button clicked, the input is sent to the Java Console using the Java classes
package.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Function takes the users input and writes it out to
// the Java Console
function writeOut(input){
Packages.java.lang.System.out.println(input);
}
// -->
</script>
<form name=“form1”>
This script takes the text input and writes it out to the Java Console
using the Java package.
<br><br>
<input type=“text” size=“40” name=“txt”>
<br><br>
<input type=“button” value="Write Out Text" name=“button1”
onClick='writeOut(document.form1.txt.value)'>
<br>
</form>
</body>
</html>
JavaScript 1.1+
Nav3+, NES2+
Packages.className
The className
property of the Packages
object is used to access classes in packages other than netscape
, sun
, or java
. Just specify the fully qualified name of the package you want to access for className
.
Listing 7.291 shows an example for accessing a fictitious class using the className
property.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Access the class: myClass.
myName = new Packages.myClass.Car()
// -->
</script>
</body>
</html>
JavaScript 1.1+
Nav3+, NES2+
Packages.java.className.methodName
The java
sub-package of the Packages
object refers to the JavaPackage
containing the core Java class library. This sub-package is used for several things, but most notably for adding security to LiveConnect and accessing the Java Console.
Listing 7.292 shows an example for the java
sub-package. It is used to write text to the Java Console.
<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--
// Use the Java sub-package to write text to the Java Console.
Packages.java.lang.System.out.println("Hello World!");
// -->
</script>
</body>
</html>
JavaScript 1.1+
Nav3+, NES2+
Packages.netscape.className.methodName
The netscape
sub-package of the Packages
object refers to the JavaPackage
containing the netscape
package. This sub-package is used by Java applets to access JavaScript code via LiveConnect. The package itself has two classes: plugin
and javascript
.
Use of this package occurs within the code of a Java applet, and not JavaScript code. However, Listing 7.293 shows an example of calling the netscape
package directly to verify it is implemented in the operating browser.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Call the package to see if it exists.
if(Packages.netscape){
document.write("This browser has LiveConnect!");
}else{
document.write("This browser does not have LiveConnect!");
}
// -->
</script>
</body>
</html>
JavaScript 1.1+
Nav3+, NES2+
Packages.sun.className.methodName
The sun
sub-package of the Packages
object refers to the JavaPackage
for the sun
property. This sub-package is used for several things, but most notably for adding security to LiveConnect.
Use of this package occurs within the code of a Java applet, and not JavaScript code. However, Listing 7.294 shows an example of calling the sun
package directly to verify it is implemented in the operating browser.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Call the package to see if it exists.
if(Packages.sun){
document.write("This browser has LiveConnect!");
}else{
document.write("This browser does not have LiveConnect!");
}
// -->
</script>
</body>
</html>
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
paraseFloat (string)
The parseFloat()
function is used to convert a string to a number.
Listing 7.295 shows how the parseFloat()
is used. In the example, parseFloat()
is called with two different strings. The first string, which contains numeric characters, is converted into a number without any problem. The second string, which contains alphabetic characters, is unable to be converted into a number.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Convert the "1245.31" string to a number.
document.write("The string 1245.31 converted is"
+ parseFloat("1245.31") + "<br>");
// Try to convert the string “test” to a number.
// If not possible, then print error.
if( isNaN(parseFloat(“test”)) ){
document.write("Cannot convert test string to a number.");
}
// -->
</script>
</body>
</html>
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
parseInt(string, radix)
parseInt(string)
The parseInt()
method is used to convert a string to an integer. It can take string
input with an optional radix
input. The radix
input represents the base of the number in the string.
Listing 7.296 shows how parseInt()
is used to parse a string. A few different examples are shown for different types of strings.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Converts the “859” string to an integer.
document.write("The string 859 converted to an integer is: ");
document.write(parseInt(“859”) + "<br>");
// Converts a binary string into an integer.
document.write("The binary string 101101 converted to an integer is: ");
document.write(parseInt(“101101”, 2) + "<br>");
// Converts a hexidecimal string into an integer.
document.write("The hexidecimal string FA832B converted to an integer is: ");
document.write(parseInt(“FA832B”, 16) + "<br>");
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+
Reserved Keyword
The private
keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.2
Nav4+, NES3+
Reserved Keyword
The protected
keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.2+
Nav4+, NES3+
Reserved Keyword
The public
keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
var variable = new RegExp(pattern, flags)
The RegExp()
object represents a regular expression that is used for pattern matching. The creation of the object takes pattern
and flags
parameters. The pattern
is a valid regular expression. The flags
are either or both g
(global) and i
(ignore case). Table 7.43 displays the properties and methods of the RegExp()
object.
Listing 7.297 shows how to use the RegExp
object. The user is given an input field, which is used to input a Social Security Number (SSN
). Once entered, the Validate button is clicked, which checks whether the input is valid. This is performed by using a RegExp
object for the SSN
.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Function checks to see if the ssn is valid.
function isSSN(str){
// Define a RegExp object which checks for either
// a 9 digit input or an input in the form:
// xxx-xx-xxxx
var regexp = /ˆ(d{9}|d{3}-d{2}-d{4})$/;
return regexp.test(str);
}
// Checks the SSN input.
function checkInput(){
var valid = true;
var ssn = document.form1.ssn.value;
if (!isSSN (ssn)){
window.alert("Invalid SSN: " + ssn);
valid = false;
}
else{
alert(ssn + " is a valid SSN");
}
}
// -->
</script>
<form name=“form1”>
Enter your SSN:
<input type=“text” size=“15” name=“ssn”>
<br><br>
<input type=“button” value="Validate SSN" onClick='checkInput()'>
<br>
</form>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
RegExp, $*
The RegExp,$*
property reflects a multiline
string search. This is a Boolean, read-only value that reflects whether strings should be searched across multiple lines. This is the same as using the multiline
property.
Listing 7.298 shows how to use RegExp,$*
for pattern matching.
<html>
<script type=“text/javascript” language=“javascript”>
<!--
// Function checks for the “the” expression. However, if
// multiple lines are read, an alert box is displayed
// indicating so.
function getinfo(){
var myPat = new RegExp(“the”, “i”);
var str = document.form1.mytext.value;
myArray = myPat.exec(str);
alert("RegExp.$* is: " + RegExp["$*"]);
}
// -->
</script>
<body>
<form name=“form1”>
When the text in the text box is changed, and the document is clicked,
an alert box will be displayed showing the value of RegExp.$*.
<br><br>
<textarea name=“mytext” cols=“60” rows=“8” onChange='getinfo()'>
This is a sample textarea containing some dummy text for
testing purposes. The text in this box will be used to
demonstrate how the multiline property is used. If multiple lines are
read, then RegExp.$* will be true.
</textarea>
<br>
</form>
</body>
</html>
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
RegExp.$&
The RegExp.$&
property represents the last matched characters. This is the same as using the lastMatch
property.
Listing 7.299 shows how RegExp.$&
is used.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Define a pattern to search for.
var pat = new RegExp(“test”, “gi”);
str = "Testing Testing 123";
myArray = pat.exec(str);
// Once pattern is found, display message.
document.write("Pattern found: " + myArray[0] +
". the last match expression ($&) is: " + RegExp["$&"]);
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
RegExp,$ _
The RegExp,$_
property represents the input to which a string is matched. This is the same as using the input
property.
Listing 7.300 shows how to use the RegExp,$_
property.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Function creates a new regular expression and
// then executes it against the text in the textbox.
// Outputs an alert message indicating the value
// of the RegExp.input property.
function getinput(){
var myPat = new RegExp(“the”, “i”);
var str = document.form1.mytext.value;
myArray = myPat.exec(str);
alert("The RegExp$ is: " + RegExp["$_"]);
}
// -->
</script>
<form name=“form1”>
When the text in the text box below is changed, an alert message
will appear showing the value of the input.
<br><br>
Enter some Text:
<input type=“text” name=“mytext” size=“40” onChange='getinput()'>
<br>
</form>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
RegExp.$`
The RegExp.$`
property represents the substring preceding the most recent pattern match. This is the same as using the leftContext
property.
Listing 7.301 shows how to use RegExp.$`
.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Define a regular expression pattern and match globally.
pat = /is*/g;
// Create a string object.
var str = "I know where the fish is tonight.";
// Create an array to hold the results.
myArray = pat.exec(str);
document.write("Check for the substring " + "<i>" + “is” + "</i>");
document.write("preceeding most recent pattern match");
document.write("In the string: " + "<b>");
document.write("I know where the fish is tonight" + "</b><br><br>");
document.write("The RegExp. $` is: " + RegExp["$`"]);
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
RegExp.$'
The RegExp.$'
property represents the substring following the most recent pattern match. This is the same as using the rightContext
property.
Listing 7.302 shows how to use RegExp.$'
.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Define a regular expression pattern and match globally.
pat = /be*/gi;
// Create a string object.
var str = "Eat Drink and be Merry.";
// Create an array to hold the results.
myArray = pat.exec(str);
document.write("Check for the substring " + "<i>" + “be” + "</i>");
document.write("following the most recent pattern match");
document.write("In the string: " + "<b>" +
"Eat Drink and be Merry" + "</b><br><br>");
document.write("The RegExp$' is: " + RegExp["$'"]);
// -->
</script>
</body>
</html>
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
RegExp.$+
The RegExp.$+
property represents the last parenthesized substring pattern match. This is the same as using the lastParen
property.
Listing 7.303 shows how RegExp.$+
is used.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Define a regular expression.
exp = new RegExp("(please)", “g”);
// Create a string object.
str = "Will you (please) stop yelling!";
myArray = exp.exec(str);
// Inform user what the lastParen property is.
document.write("The RegExp.$+is: " + "<b>"
+ RegExp["$+"]+ "</b>");
// -->
</script>
</body>
</html>
JavaScript 1.2+, JScript 1.0+
Nav4+, NES3+, IE4+
RegExp.$1,$2,..$9
The RegExp.$1,$2,..$9
property represents parenthesized substring matches.
Listing 7.304 shows how RegExp.$1,$2,..$9
is used. The user will enter his phone number in the input text box and, when the button is clicked, the swap
function swaps the last four digits in the phone number with the first three.
<html>
<script type=“text/javascript” language=“javascript”>
<!--
// Function takes the input and swaps the last 4 digits with the
// first three digits.
function swap(){
re = /(w+)D(w+)/;
str = document.form1.text1.value;
newstr=str.replace(re, "$2, $1");
document.form1.text2.value = newstr;
}
// -->
</script>
<body>
<form name=“form1”>
Enter your 7 digit phone number in the form xxx-xxxx
<br><br><br>
Phone Number (7 digits):<input type=“text” name=“text1” size=“10”>
<br><br>
<input type=“button” value=“Swap” onClick='swap()'>
<br><br><br>
Output: <input type=“text” name=“text2” size=“10”>
</form>
</body>
</html>
JavaScript 1.1+, JScript 3.0+
Nav3+, NES2+, IE4+, Opera5+
regexp.constructor
The constructor
property of the RegExp
object specifies the function that creates the object.
Listing 7.305 shows how the constructor property is used to create a RegExp
object.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Create a new RegExp object using the constructor property.
myExp = new RegExp(“the”)
if(myExp.constructor == RegExp){
document.write("Object is created");
}
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
regexp.compile(pattern, flag)
The compile()
method of the RegExp
object compiles a regular expression object. The creation of the object takes pattern
and flags
parameters. The pattern
is a valid regular expression. The flags
are either or both g
(global) and i
(ignore case).
Listing 7.306 shows how to use the compile()
method. A pattern is created using the RegExp
constructor. It is then compiled using the compile()
method, and the result is displayed in the text area.
<html>
<script type=“text/javascript” language=“javascript”>
<!--
var myPat = new RegExp(“jane”, “i”);
var newPat = myPat.compile(myPat);
// function displays the result of the compiled pattern.
function getinfo(){
document.form1.text1.value = newPat;
}
// -->
</script>
<body>
<form name=“form1”>
Click the button below to get the pattern for the following
command: new RegExp(“jane”, “i”);
<br><br><br>
Compiled Pattern: <input type=“text” name=“text1” size=“30”>
<br><br>
<input type=“button” value="Get Pattern" onClick='getinfo()'>
</form>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
regexp.exec (string)
The exec()
method of the RegExp
object executes the search for a match in a specified string. The results are returned in an array. The string
passed contains the string the regular expression is trying to match in.
In Listing 7.307, you see how the exec()
method is used. A regular expression is defined and executed on the string using the exec()
method.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Checks for the pattern “xyz” in str. If found, then
// output written to document indicating that it was found and
// displays the index it was found in the string.
myRe=/xyz*/g;
str = “abcxyzdefhij”
myArray = myRe.exec(str);
document.writeln("Found " + myArray[0] + " in the pattern: " + "<b>" +
"abcxyzdefhij " + "</b>" + " at index " +
(myRe.lastIndex - 3));
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
regexp.global
The global
property of the RegExp
object specifies whether the g
flag is used with the regular expression. If so, a global pattern match will be performed.
Listing 7.308 shows how the global
property is used. A new RegExp
object is created specifying the global
option. When the script is loaded, the expression is checked and the value of the global
property is printed out.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Defines a regular expression on the pattern “if”
// with the global flag set.
var myPat = new RegExp(“if”, “g”);
// Define a string.
var str = "What if Angela is wondering about gifs?";
// Store results of exec into myArray.
myArray = myPat.exec(str);
document.write("The value of RegExp.global is: " + "<b>"
+ myPat.global + "</b>");
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
regexp.ignoreCase
The ignoreCase
property of the RegExp
object is a flag that informs the user whether case is to be ignored during pattern matching.
Listing 7.309 shows how ignoreCase
is used. A new RegExp
object is created specifying the ignoreCase
option. When the script is loaded, the expression is checked and according to the value of the ignoreCase
property, an appropriate message is displayed.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Defines a regular expression on the pattern “and”
// with the ignore case flag set.
var myPat = new RegExp(“and”, “i”);
// Define a string.
var str = "Would Missy and Livvy like some Candy?";
// Store results of exec into myArray.
myArray = myPat.exec(str);
if (myPat.ignoreCase == true){
document.write("The " + "<i>" + “ignoreCase” + "</i>" + " option WAS
used");
}
else{
document.write("The " + "<i>" + “ignoreCase” + "</i>" + " was NOT used");
}
// -->
</script>
</body>
</html>
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
regexp.input
The input
property of the RegExp
object represents the string on which the pattern matching is performed.
Listing 7.310 shows how to use the input
property.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Function creates a new regular expression and
// then executes it against the text in the textbox.
// Outputs an alert message indicating the value
// of the RegExp.input property.
function getinput(){
var myPat = new RegExp(“the”, “i”);
var str = document.form1.mytext.value;
myArray = myPat.exec(str);
alert("The RegExp.input is: " + RegExp.input);
}
// -->
</script>
<form name=“form1”>
When the text in the text box below is changed, an alert message
will appear showing the value of the input.
<br><br>
Enter some Text:
<input type=“text” name=“mytext” size=“40” onChange='getinput()'>
<br>
</form>
</body>
</html>
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
regexp.lastIndex
The lastIndex
property of the RegExp
object is used to get the index of where the next match begins.
Listing 7.311 shows how the lastIndex
property is used. A regular expression for “is”
is created and checked against the string. When found, results are written to the document.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
</script>
// Creates a regular expression for “is”.
exp=/is*/g;
str = "This is just a sample sentence.";
myArray = exp.exec(str);
document.write("Found: " + myArray[0] +
". Next match starts at index: " + exp.lastIndex);
// -->
</script>
</body>
</html>
JavaScript 1.2+, JScript 5.5+
Nav4+, NES3+, IE4+
regexp.lastMatch
The lastMatch
property of the RegExp
object represents the last matched characters.
Listing 7.312 shows how the lastMatch
property is used. A RegExp
object is created to look for the string “test”
within the str
variable. Upon loading the document, the lastMatch
property will display the last pattern to be matched.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Define a pattern to search for.
var pat = new RegExp(“test”, “gi”);
str = "Testing Testing 123";
myArray = pat.exec(str);
// Once pattern is found, display message.
document.write("Pattern found: " + myArray[0] +
". the last match expression is: " + RegExp.lastMatch);
// -->
</script>
</body>
</html>
JavaScript 1.2+, JScript 5.5+
Nav4+, NES3+, IE4+
regexp.lastParen
The lastParen
property of the RegExp
object represents the last parenthesized substring match. It returns a string value for the last parenthesized substring.
Listing 7.313 shows how the lastParen
property is used.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Define a regular expression.
exp = new RegExp("(please)", “g”);
// Create a string object.
str = "Will you (please) stop yelling!";
myArray = exp.exec(str);
// Inform user what the lastParen property is.
document.write("The RegExp.lastParen is: " + "<b>"
+ RegExp.lastParen + "</b>");
// -->
</script>
</body>
</html>
JavaScript 1.2+, JScript 5.5+
Nav4+, NES3+, IE4+
regexp.leftContext
The leftContext
property of the RegExp
object represents the substring preceding the most recent pattern match.
Listing 7.314 shows how the leftContext
property is used. A RegExp
pattern is used to get all the contents of the string before the is
pattern.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Define a regular expression pattern and match globally.
pat = /is*/g;
// Create a string object.
var str = "I know where the fish is tonight.";
// Create an array to hold the results.
myArray = pat.exec(str);
document.write("In the string: " + "<b>" +
"I know where the fish is tonight" + "</b><br><br>");
document.write("The RegExp.leftContext is: " + RegExp.leftContext);
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
regexp.multiline
The multiline
property of the RegExp
object is used to determine whether pattern matching should be performed across multiple lines.
Listing 7.315 shows how multiline
is used.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Function creates a new regular expression and
// then executes it against the text in the textarea.
// Outputs an alert message indicating the boolean value
// of the RegExp.multiline property.
function getinfo(){
var myPat = new RegExp(“the”, “i”);
var str = document.form1.mytext.value;
myArray = myPat.exec(str);
alert("RegExp.multiline is: " + RegExp.multiline);
}
// -->
</script>
<form name=“form1”>
When the text in the text box is changed, and the document is clicked,
an alert box will be displayed showing the value of RegExp.multiline.
<br><br>
<textarea name=“mytext” cols=“60” rows=“8” onChange='getinfo()'>
This is a sample textarea containing some dummy text for
testing purposes. The text in this box will be used to
demonstrate how the multiline property is used. If multiple lines are
read, then RegExp.multiline will be true.
</textarea>
<br>
</form>
</body>
</html>
JavaScript 1.1+
Nav3+, NES2+, Opera4+
regexp.prototype.property
regexp.prototype.method
The prototype
property of the RegExp
object allows you to add properties or methods to all instances of this class. After properties or methods have been added, any future instances of the object will contain the newly created prototype property.
Listing 7.316 shows how the prototype
property is used to create a new property named myProp
. Then the property is assigned a value and displayed.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Create a new property called myProp.
RegExp.myProp = null;
// Create a new RegExp object that contains the new property.
var myExp = new RegExp(“now”);
myExp.myProp = "nothing special";
document.write("The value of myProp is: " + myExp.myProp);
// -->
</script>
</body>
</html>
JavaScript 1.2+, JScript 5.5+
Nav4+, NES3+, IE4+
regexp.rightContext
The rightContext
property of the RegExp
object represents the substring following the most recent pattern match.
Listing 7.317 shows how the rightContext
property is used. A pattern is defined so that all the contents of the string that appear after the be
pattern will be displayed.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Define a regular expression pattern and match globally.
pat = /be*/gi;
// Create a string object.
var str = "Eat Drink and be Merry.";
// Create an array to hold the results.
myArray = pat.exec(str);
document.write("In the string: " + "<b>" +
"Eat Drink and be Merry" + "</b><br><br>");
document.write("The RegExp.rightContext is: " + RegExp.rightContext);
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
regexp.source
The source
property of the RegExp
object represents the text of the pattern being used for pattern matching.
Listing 7.318 shows how the source
property can be used to get the pattern being matched.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Create a new RegExp object.
exp = new RegExp(“am”, “g”);
// Create a string.
str = "This is just a sample sentence.";
myArray = exp.exec(str);
document.write("The source is: " + "<b>" + exp.source + "</b>");
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+, IE4+
regexp.test()
The test()
method of the RegExp
object is used to test for a pattern match in a string. Returns boolean value true
or false
.
Listing 7.319 shows how the test()
method is used.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Create a new regular expression.
myExp = new RegExp(“hope”, “g”);
// Define a string object.
str = "I hope everything is going well.";
// Test to see if the regular expression exists in the string.
if(myExp.test(str)){
document.write("The test found "hope" in the string: "
+ "<b>" + " I hope everything is going well" + "</b>");
}
// -->
</script>
</body>
</html>
JavaScript 1.3+, ECMAScript 1E+
Nav4.06+
regexp.toSource()
The toSource()
method of the Number
object is used to get a string representation of the Number
object.
Listing 7.320 shows how the toSource()
method is used.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Creates a new RegExp object and then gets the string
// representation of that object.
var myExp = RegExp(“the”);
document.write(myExp.toSource());
// -->
</script>
</body>
</html>
JavaScript 1.1+, ECMAScript 1E+
Nav3+, NES2+, IE4+, Opera3+
regexp.toString()
The toString()
method of the RegExp
object is used to get a string representation of the RegExp
object.
Listing 7.321 shows how the toString()
method is used.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Create a new RegExp object.
var myExp = RegExp(“and”);
// Display the string representation of myExp.
document.write("The RegExp toString output is: " + "<b>" + myExp.toString() +
"</b>");
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+
regexp.unwatch(prop)
The unwatch()
method of the RegExp
object will remove a watch point on a property set by the watch()
method.
Listing 7.322 shows an example for the unwatch()
method. A property is created using the prototype()
method. Then a watch point is placed on the newly created property and a message is displayed when the watch point is hit. When the unwatch()
method is called, the watch point is removed.
<html>
<body>
<script "type=“text/javascript” language=“javascript”>
<!--
function alertme(id,oldValue,newValue)
{
document.writeln("myExp." + id + " changed from " + "<b>" + oldValue +
"</b>"+ " to " + "<b>" + newValue + "</b><br>")
return newValue;
}
myExp = new RegExp(“and”);
// Create new property p.
RegExp.prototype.p = “the”;
// Set the watchpoint on p.
myExp.watch(“p”,alertme);
myExp.p = “or”;
// Remove the watchpoint on p.
myExp.unwatch(“p”);
myExp.p = “cat”;
myExp.p = “dog”;
// Set the watchpoint on p again.
myExp.watch(“p”,alertme);
myExp.p = “cow”;
// -->
</script>
</body>
</html>
JavaScript 1.1+
Nav3+, NES2+, IE4+
regexp.valueOf()
The valueOf()
method of the RegExp
object is used to get the primitive value of a RegExp
object as a number data type.
Listing 7.323 shows an example for the valueOf()
method. A RegExp
object is created and set to myExp
. The document then outputs the result of performing a valueOf
function on the RegExp
object.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
// Create a new number object.
myExp = new RegExp(“or”);
// Output the valueOf result.
document.write("The value of myExp is: " + myExp.valueOf());
// -->
</script>
</body>
</html>
JavaScript 1.2+
Nav4+, NES3+
regexp.watch(prop, handler)
The watch()
method of the RegExp
object will watch for an assignment to a specific property. When an assignment is made, a specified handler will be called to perform a user-defined operation.
Listing 7.324 shows an example for the watch()
method. A new property is created using the prototype
method. Then a watch point is set on the newly created property. When an assignment is made, the alertme
function will be called to display a message.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
function alertme(id,oldValue,newValue)
{
document.writeln("myExp." + id + " changed from " + "<b>" +
oldValue + "</b>"+ " to " + "<b>" + newValue + "</b><br>")
return newValue;
}
myExp = new RegExp(“and”);
// Create a new property p.
RegExp.prototype.p = “the”;
// Set a watchpoint on p.
myExp.watch(“p”,alertme);
myExp.p = “or”;
// -->
</script> type="text
</body>
</html>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
return
The return
keyword will exit the existing function and return a value.
Listing 7.325 shows an example of using the return
statement to return the value of the processing from the function.
<html>
<body>
<script type=“text/javascript” language=“javascript”>
<!--
//Function to get the value of 4 times 3.
function getValue(){
var myValue = 4*3;
return myValue;
}
// Function calls getValue() and fills the tmp input box element
// with the value returned.
function fill(){
var x = getValue();
document.form1.tmp.value = x;
}
// -->
</script>
<form name=“form1”>
Value: <input type=“text” Name=“tmp” Size=“5”>
<br>
<br>
<input type=“button” name=“get” value="Get Returned Value" onClick='fill()'>
<br>
<br>
</form>
</body>
</html>
JScript 2.0+
ScriptEngine()
The ScriptEngine()
function has three possible return values: JScript
, VBScript
, and VBA
. When implemented in JavaScript scripts, this function returns JScript
.
Listing 7.326 prints the complete version information for the Internet Explorer browser interpreting the script. In addition to the ScriptEngine
property, it also uses other Internet Explorer specific functions.
<script type="text/jscript">
<!--
// Write the scripting engine type.
document.write(ScriptEngine());
// Write the “major” version value to the page.
document.write(" " + ScriptEngineMajorVersion() + ".");
// Write the “minor” version value to the page.
document.write(ScriptEngineMinorVersion());
// Write the build number to the page.
document.write(" build " + ScriptEngineBuildVersion());
//-->
</script>
JScript 2.0+
ScriptEngineBuildVersion
The ScriptEngineBuildVersion()
function contains the actual build number of the scripting engine contained on the user’s machine.
Listing 7.327 prints the build number of the scripting engine interpreting the script.
<script type="text/jscript">
<!--
// Write the build number to the page
document.write("Build " + ScriptEngineBuildVersion());
//-->
</script>
JScript 2.0+
ScriptEngineMajorVersion()
The ScriptEngineMajorVersion()
function contains the actual major version number of the scripting engine contained on the user’s machine.
Listing 7.328 prints the major version number of the scripting engine interpreting the script.
<script type="text/jscript">
<!--
// Write the build number to the page
document.write("Major Version: " + ScriptEngineMajorVersion());
//-->
</script>
JScript 2.0+
ScriptEngineMinorVersion()
The ScriptEngineMinorVersion()
function contains the actual minor version number of the scripting engine contained on the user’s machine.
Listing 7.329 prints the minor version number of the scripting engine interpreting the script.
<script type="text/jscript">
<!--
// Write the build number to the page.
document.write("Minor Version: " + ScriptEngineMinorVersion());
//-->
</script>
JavaScript 1.2+
Nav4+, NES3+
Reserved Keyword
The short
keyword has not been implemented in JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.2+
Nav4+, NES3+,
Reserved Keyword
The static
keyword has not been implemented in JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.2+, JScript 3.0+, ECMAScript 1E+
Nav4+, NES3+, IE4+, Opera4+
String (var)
The String()
function is a top-level function, which is often of the Global
object. It converts the value of any var
into a readable string.
In Listing 7.330, we will create an instance of the Date
object, and then use the String()
function to write out a readable string version of the date.
<script type=“text/javascript” language=“JavaScript1.2”>
<!--
// Create an instance of Date object.
myDate = new Date (430057843027);
// writes Thu Aug 18 07:30:43 EST 1983
document.write(String(myDate));
//-->
</script>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
var variable = new String(string) JavaScript1.1+
“string”
The String
object is one of the core JavaScript objects. Instances are created when a program constructs an instance using the new
keyword and passing it the String
object. In JavaScript 1.0, instances were also created when programmers quoted characters in their script. Table 7.44 lists the properties and methods used by this object.
Listing 7.331 displays the use of some of the String
properties and methods. It contains a single button. After the user clicks the button, a second window is opened. Various methods are called by a string instance created in the script. The results of such are displayed in the pop-up window.
<html>
<head>
<title>Examples of the String Object</title>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Define the openWin function called by pressing the button.
function openWin(){
// Open a window to store the results and create a new String object.
var myWin = open("", "","width=450,height=200");
var myString = new String("Hello, World!");
// Call various methods on this instance and write their results to the
// window.
myWin.document.write("Original String, " + myString); myWin.document.write(" has " + myString.length + " characters.<br>");
myWin.document.write("Big: " + myString.big() + "<br>");
myWin.document.write("Small: " + myString.small() + "<br>");
myWin.document.write("Blinking: " + myString.blink() + "<br>");
myWin.document.write("Italics: " + myString.italics() + "<br>");
myWin.document.write("Convert to Lower: " + myString.toLowerCase());
myWin.document.write("<br>");
myWin.document.write("Convert to Upper: " + myString.toUpperCase());
myWin.document.write("<br>");
// Close the stream to the window.
myWin.document.close();
}
//-->
</script>
</head>
<body>
<form name=“myForm”>
<input type=“button” value="Click to Process" name=“myButton”
onClick="openWin()">
</form>
</body>
</html>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.anchor(name)
The anchor()
method will convert the string it is called on to an instance of the <a>
tag, setting the name
attribute to the name that is passed.
Listing 7.332 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<a name=“HELLO”>YHello, World!</a>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the big() method on it.
document.write(myString.anchor(“HELLO”));
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.big()
The big()
method will convert the string it is called on to an instance of the <big>
tag.
Listing 7.333 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<big>Hello, World!</big>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the anchor() method on it.
document.write(myString.anchor(“HELLO”));
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+
Nav2+, NES2+
string.blink()
The blink()
method will convert the string it is called on to an instance of the <blink>
tag. This method is only supported in Netscape Navigator because it is the only browser that has an implementation of the <blink>
tag.
Listing 7.334 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<blink>Hello, World!</blink>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the blink() method on it.
document.write(myString.blink());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.bold()
The bold()
method will convert the string it is called on to an instance of the <bold>
tag.
Listing 7.335 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<bold>Hello, World!</bold>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the bold() method on it.
document.write(myString.bold());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
string.charAt(num)
The charAt()
method of an instance of the String
object returns the character located at the indexed,num, position passed. This indexing is done from left to right starting with the 0 (zero) position. If the num passed is not a valid index in the string, –1 is returned.
Listing 7.336 creates an instance of a String
object. When the page is loaded, the user is prompted for an index number. After entering the index number and clicking OK, the character at that indexed location is written to the document. Notice that there is also a check to see whether the character at that location is a space.
<html>
<head>
<pre>
<title>Using the String.charAt() method</title>
</head>
<body>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Here is a short sentence.");
// Prompt the user for a number.
var myIndex = prompt("Please enter a number", "");
// Store the character at that location in a variable.
var myChar = myString.charAt(myIndex);
// Write the character to the page, but check to see if it
// is a space first.
document.write('<b>The string you searched through was: </b>' + myString);
document.write('<br>The ' + myIndex + ' character in this string is '),
if (myChar == " "){
document.write('<space>'),
}else{
document.write(myChar);
}
// Close the stream to the window.
myWin.document.close();
//-->
</script>
</body>
</html>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
string.charCodeAt(num)
The charCodeAt()
method of an instance of the String
object returns the ISO-Latin-1 number of the character located at the indexed,num, position passed. This indexing is done from left to right starting with the 0 (zero) position. If the num passed is not a valid index in the string, –1 is returned.
Listing 7.337 creates an instance of a String
object. When the page is loaded, the user is then prompted for an index number. After entering the index number and clicking OK, the ISO-Latin-1 number of the character at that indexed location is written to the document. Notice that there is also a check to see whether the character at that location is a space.
<html>
<head>
<title>Using the String.charCodeAt() method</title>
</head>
<body>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Here is a short sentence.");
// Prompt the user for a number.
var myIndex = prompt("Please enter a number", "");
// Store the character code at that location in a variable.
var myCharCode = myString.charCodeAt(myIndex);
var myChar = myString.charAt(myIndex);
// Write the character code to the page.
document.write('<b>The string you searched through was: </b>' + myString);
document.write('<br>The ' + myIndex + ' character in this string is '),
// Check to see if it is a space.
if (myChar == " "){
document.write('<space>'),
}else{
document.write(myChar);
}
// Write the character code.
document.write(' and its ISO-Latin-1 code is ' + myCharCode);
// Close the stream to the window.
myWin.document.close();
//-->
</script>
</body>
</html>
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
string.concat(string2)
The concat()
method of an instance of the String
object concatenates the string in string2 to the end of string to return a new string.
Listing 7.338 creates two instances of the String
object and uses the concat()
method to concatenate them to create a new string. The string is then displayed in an alert box.
<script type=“text/javascript” language=“JavaScript1.2”>
<!--
// Create 2 instances of the String object and concatenate
// them together.
var myString1 = new String("Hello, ");
var myString2 = new String("World!");
var myConcatString = myString1.concat(myString2);
// Popup an alert box showing the concatenation.
alert(myConcatString);
//-->
</script>
JavaScript 1.1+, JScript 3.0+, ECMAScript 1E+
Nav3+, NES2+, IE4+, Opera3+
string.constructor
The constructor
property of the String
object specifies the function that creates the object.
Listing 7.339 shows an example of the constructor
property, which is used to check the type of variable.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object. var myString = new String("Hello, World!");
if(myString.constructor == String){ document.write("Object created"); }
//--> </script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.fixed()
The fixed()
method will convert the string it is called on to an instance of the <tt>
tag.
Listing 7.340 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<tt>Hello, World!</tt>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the fixed() method on it.
document.write(myString.fixed());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.fontcolor (hexnum)
string.fontcolor(color)
The fontcolor()
method sets the color
attribute of an instance of the <font>
tag, which it creates. This attribute can either be passed as the hexadecimal equivalent of the color or the actual string that represents that color.
Listing 7.341 creates an instance of the String
object and uses the document.write()
method to write two instances of the tag to the page. The results of running this script will be the following:
Hex usage: <font color="#FF0000">Hello, World!</font>
Color usage: <font color=“blue”>Hello, World!</font>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string twice to the page after invoking the
// fontcolor() method on them.
document.write("Hex usage: " + myString.fontcolor('FF0000'));
document.write("<br>Color usage: " + myString.fontcolor(‘blue’));
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.fontsize(num)
string.fontsize(string2)
The fontsize()
method sets the size
attribute of an instance of the <font>
tag, which it creates. This attribute can be a number between 1 and 7. If you pass the method the number in the form of a string, the size displayed is relative to the <basefont>
tag.
Listing 7.342 creates an instance of the String
object and uses the document.write()
method to write two instances of the tag to the page. The results of running this script will be the following:
Hex usage: <font size=“6”>Hello, World!</font>
<br>Color usage: <font size="-2">Hello, World!</font>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string twice to the page after invoking the
// fontsize() method on them.
document.write("Size=6: " + myString.fontsize(6));
document.write("<br>Size=-2: " + myString.fontsize('-2'));
// Close the stream to the window.
document.close();
//-->
</script
JavaScript 1.2+, JScript 3.0+, ECMAScript 1E+
Nav4+, NES3+, IE4+
String.fromCharCode(num1, num2, …, numN)
String.fromCharCode(keyevent.which)
The fromCharCode()
method of the String
object returns the characters that correspond to the ISO-Latin-1 numbers (num1,num2, …
,numN) position passed. You can also pass the method a key event and use the which
property to determine which key has been pressed. The possible key events are KeyDown
, KeyPress
, and KeyUp
.
As you can see in the syntax definition, this is a method of the actual String
object and not an instance of this object. Because of this, you might want to store the results generated by this method into a variable for future processing.
Listing 7.343 invokes the fromCharCode()
method on the numbers 88
, 89
, and 90
. The results of this processing are then written to the user’s page.
<script type=“text/javascript” language=“JavaScript1.2”>
<!--
// Invoke the fromCharCode() method and store the results in
// a variable.
var myString = String.fromCharCode(88,89,90);
// Write the results to the page.
document.write("These numbers evaluate to: " + myString);
// Close the stream to the page.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
string.indexOf(string, num)
string.indexOf(string)
The indexOf()
method of an instance of the String
object returns the indexed start position of the string passed. Additionally, you can specify an index, defined by num in the syntax definition, to start your search for the string specified. This method is the same as the String.lastIndexOf()
method, but it starts at the beginning of the string.
Listing 7.344 creates a simple instance of the String
object. This instance is then passed to the indexOf()
method on two occasions with the result written to the user’s page. The first occasion looks for a space in the string, which returns 6
. The second occasion starts the search at the fourth position, so it returns the location of the letter“l”
in the word “world”
.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Look for the first instance of a space.
document.write(myString.indexOf(" ") + '<br>'),
// By specifying an indexed location to start looking you
// can return the indexed location of the third instance of
// the letter ‘l’.
document.write(myString.indexOf(“l”, 4));
// Close the stream to the page.
document.close();
//-->
</script>
string.italics()
The italics()
method will convert the string it is called on to an instance of the <i>
tag.
Listing 7.345 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
Hello, World!
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the italics() method on it.
document.write(myString.italics());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
string.lastIndexOf(string, num)
string.lastIndexOf(string)
The lastIndexOf()
method of an instance of the String
object returns the indexed start position of the string passed, starting from the right and going left. Additionally, you can specify an index, defined by num
in the syntax definition, to start your search for the string specified. This method is the same as the String.indexOf()
method, but it starts at the end of the string.
Listing 7.346 creates a simple instance of the String
object. This instance is then passed to the lastIndexOf()
method on two occasions with the result written to the user’s page. The first occasion looks for the last occurrence of the letter e
in the string, which returns 16
. The second occasion starts the search at the third position, so it returns the location of the first l
in the word “Hello”
.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello World, here I am!");
// Look for the last instance of the letter ‘e’.
document.write(myString.lastIndexOf(“e”) + '<br>'),
// By specifying an indexed location to start looking, you
// can return the indexed location of the first instance of
// the letter ‘l’.
document.write(myString.lastIndexOf(“l”, 3));
// Close the stream to the page
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
string.length
The length
property of an instance of the String
object returns the total length of the string.
Listing 7.347 creates three instances of the String
object. The length
property of each of these instances is accessed and written to the user’s page.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString1 = new String("Hello, World");
var myString2 = new String("Here is a longer string");
var myString3 = new String("Here is an even longer string");
// Write the lengths of these strings to the user’s page.
document.write(myString1 + ": is " + myString1.length);
document.write(" characters long.<br>");
document.write(myString2 + ": is " + myString2.length);
document.write(" characters long.<br>");
document.write(myString3 + ": is " + myString3.length);
document.write(" characters long.<br>");
// Close the stream to the page.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.link(URL)
The link()
method will convert the string it is called on to an instance of the <a>
tag, setting the href
attribute to the URL that is passed.
Listing 7.348 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<a href="http://www.purejavascript.com">The online book!</a>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("The online book!");
// Write the string to the page after invoking the link() method on it.
document.write(myString.link('http://www.purejavascript.com'));
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.5+, ECMAScript 3E+
Nav6
string.localeCompare (string2)
The localeCompare()
method of an instance of the String
object compares string against string2. The resulting numerical value, which can be negative, zero, or positive, orders the strings in a sort order specified by the system default locale.
In Listing 7.349, two strings are created and the localeCompare()
method is called to compare them.
<script type=“text/javascript” language="JavaScript1.5">
<!--
// Define two strings.
myString = new String(“hello”)
myString2 = new String(“world”)
// Returns –15 in Netscape 6.
document.write(myString.localeCompare(myString2));
//-->
</script>
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
string.match (regexpression)
The match()
method of an instance of the String
object searches the string in which it is invoked for the regular expression passed to the method. The regexpression is made up of a pattern and flags that dictate what is to be matched. The method returns an array containing the matches found in the string.
Listing 7.350 creates an instance of the String
object and tries to match instances that contain a space followed by some characters. If any matches were returned into the array, they are written to the user’s page one at a time.
<script type=“text/javascript” language=“JavaScript1.2”>
<!--
// Create an instance of the String object and load it with a name.
var myString = new String("Mr. R. Allen Wyke");
// Match occurrences of a space followed by characters.
var myRegExp = /sw*/g;
var answerArray = myString.match(myRegExp);
// Check to see if there were any matches found.
if(answerArray == null){
document.write('No matches were found'),
}else{
document.write('The following matches were found: <br/>'),
// Write the contents of the array to the page. This will put
// R, Allen, and Wyke each on a separate line.
for(var i = 0; i < answerArray.length; i++){
document.write(answerArray[i] + '<br>'),
}
}
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES2+, IE4+, Opera3+
String.prototype.property
String.prototype.method
The prototype
property of the String
object allows a programmer to add properties or methods to a core JavaScript object.
Listing 7.351 creates two instances of the String
object. Then it prototypes a new property, type
, and a new method, verify()
. In the script, the type
property is assigned to the string instances and then they are checked using the verify()
method. The results of the validation are then written to the user’s page.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Define the method that we prototyped.
function myVerify(){
// Check to see if the type property we added is set to “Name”.
// If it is, then return true. If not, then return false.
if(this.type != “Name”){
return false;
}else{
return true;
}
}
// Create a new property and method of the String object.
String.prototype.type = null;
String.prototype.verify = myVerify;
// Create two instances of the String object and load it with a name.
var myString1 = new String("Mr. R. Allen Wyke");
var myString2 = new String("Mr. Robert J. Wyke");
// Using the prototype we defined, assign the type property to Name
// for the first string and to “Title” for the second.
myString1.type = “Name”;
myString2.type = “Title”;
// Check each of the types of the strings to see if they are valid.
if(myString1.verify()){
document.write(myString1 + " has a valid type of " + myString1.type);
}else{
document.write(myString1 + " has an invalid type of " + myString1.type);
}
document.write('<br>'),
if(myString2.verify()){
document.write(myString2 + " has a valid type of " + myString2.type);
}else{
document.write(myString2 + " has an invalid type of " + myString2.type);
}
// Close the stream to the window
//document.close();
//-->
</script>
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
string.replace(regexpression, replacestring)
The replace()
method of an instance of the String
object searches the string in which it is invoked for the regular expression passed to the method. The regexpression is made up of a pattern and flags that dictate what is to be matched. If and when a match is found, the method returns a new string with that match supplanted with the replacement string passed to the method.
Listing 7.352 creates an instance of the String
object. This instance is then searched through to see whether any occurrence of the word “Wyke”
is found. If so, it is replaced with “White”
.
<script type=“text/javascript” language=“JavaScript1.2”>
<!--
// Create an instance of the String object and load it with a name.
var myString = new String("Mr. R. Allen Wyke");
// Search for “Wyke” and replace it with “White”.
var myRegExp = /Wyke/g;
var newString = myString.replace(myRegExp, “White”);
// Write the results to the page.
document.write('Notice the last name in the original string, ' + myString);
document.write(', was replaced and is now '+ newString);
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
string.search (regexpression)
The search()
method of an instance of the String
object searches the string in which it is invoked for the regular expression passed to the method. The regexpression is made up of a pattern and flags that dictate what is to be matched. The method returns the indexed start location of the string if it is found and –1
if the string does not contain a regular expression match.
Listing 7.353 creates an instance of the String
object, which is searched for the first instance of a space. If a match is found, the indexed start position is returned. The results of running this script are written to the user’s page.
<script type=“text/javascript” language=“JavaScript1.2”,>
<!--
// Create an instance of the String object and load it with a name.
var myString = new String("Mr. R. Allen Wyke");
// Find the first occurrences of a space.
var myRegExp = /s/;
var answerIdx = myString.search(myRegExp);
// Check to see if there were any matches found.
if(answerIdx == -1){
document.write('No matches were found'),
}else{
document.write('Your search string was found starting at: ' + answerIdx);
}
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.slice(num1, num2)
string.slice(num)
The slice()
method of an instance of the String
object returns the characters in the string between the indexed positions num1 and num2 in which the method is invoked. The string itself is zero based, so the first character is in position 0
. It is also possible to pass num2 as a negative number. In this scenario, the string counts from the end of the string to end the slice.
As the syntax definition states, it is also possible to pass a single index location to the method. In this implementation, the method will not stop at a position and will return all characters until the end of the string.
Listing 7.354 creates an instance of the String
object. The slice()
method is invoked on this string and asked to return the first seven characters of the string. The results of running this script are written to the user’s page.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object and load it with a name.
var myString = new String("Mr. R. Allen Wyke");
// Grab the first 7 characters of the string.
var mySlice = myString.slice(0,6);
// Write the results to the page.
document.write('The first 7 characters of our string, ' + myString);
document.write(', are: ' + mySlice);
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.small()
Description:
The small()
method will convert the string it is called on to an instance of the <small>
tag.
Listing 7.355 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<small>Hello, World!</small>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the small() method on it.
document.write(myString.small());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.1+, JScript 1.0+, ECMAScript 1E+
Nav3+, NES2+, IE3+, Opera3+
string.split(separator, num)
string.split(separator)
string.split(regexpression, num)
string.split(regexpression)
The split()
method of an instance of the String
object splits the string in which it is invoked into separate strings based on the regexpression or separator passed to the method. If a regular expression is passed, it is made up of a pattern and flags that dictate what is to be matched. The separator is a string or character that is matched to perform the separation.
The method returns an array containing each of the segments found in the string.
Listing 7.356 creates an instance of the String
object. This instance is then split, looking for a space as the separator, using each of the syntactical definitions. The results are then written to the user’s page.
<script type=“text/javascript” language=“JavaScript1.2”>
<!--
// Define a function to handle writing the results.
function genResults(arrayName, testName){
document.write('<b>Currently Evaluating: ' + testName + '</b><hr>'),
// Check to see if there were any spaces found.
if(arrayName == null){
document.write('No matches were found'),
}else{
// Write the contents of the array to the page. This will put
// R, Allen, and Wyke each on a separate line.
for(var i = 0; i < arrayName.length; i++){
document.write('[' + i + ']: ' + arrayName[i] + '<br>'),
}
}
document.write('<p>'),
}
// Create an instance of the String object and load it with a name.
var myString = new String("Mr. R. Allen Wyke");
// Define a regular expression and a separator. Both are set to
// split on a single space.
var myRegExp = /s/g;
var mySeparator = " ";
genResults(myString.split(mySeparator), "Separator Only");
genResults(myString.split(mySeparator, 2), "Separator With Limit of 2");
genResults(myString.split(myRegExp), "Regular Expression Only");
genResults(myString.split(myRegExp, 3), "Regular Expression With Limit of 3");
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.strike()
The strike()
method will convert the string it is called on to an instance of the<strike>
tag.
Listing 7.357 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<strike“Hello, World!”/strike>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the strike() method on it.
document.write(myString.strike());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.sub()
The sub()
method will convert the string it is called on to an instance of the <sub>
tag.
Listing 7.358 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<sub>Hello, World!</sub>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the sub() method on it.
document.write(myString.sub());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.substr(num1, num2)
string.substr (num)
The substr()
method of an instance of the String
object returns the characters in the string, starting with the indexed position num1 and counting to num2 characters. The string itself is zero based, so the first character is in position 0
. It is also possible to pass num1 as a negative number. In this scenario, the string starts from the end of the string to begin the substring extraction.
As the syntax definition states, it is also possible to pass a single index location to the method. In this implementation, the method will not stop at a position and will return all characters until the end of the string.
Listing 7.359 creates an instance of the String
object. The substr()
method is invoked on this string and asked to return the first six characters of the string. The results of running this script are written to the user’s page.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object and load it with a name.
var myString = new String("Mr. R. Allen Wyke");
// Grab the first 7 characters of the string.
var mySubString = myString.substr(0,6);
// Write the results to the page.
document.write('The first 6 characters of our string, ' + myString);
document.write(', are: ' + mySubString);
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.substring(num1, num2)
string.substring(num)
The substring()
method of an instance of the String
object returns the characters in the string, starting with the indexed position num1 and ending with the character before num2. The string itself is zero based, so the first character is in position 0
.
If you pass num1 as a negative number, it will be treated as 0
. Likewise if you pass num2 as a value greater than the String.length
property, it will be treated asString.length
. And finally, if num1 equals num2, an empty string is returned.
As the syntax definition states, it is also possible to pass a single index location to the method. In this implementation, the method will not stop at a position and will return all characters until the end of the string.
Listing 7.360 creates an instance of the String
object. The substring()
method is invoked on this string and asked to return the first 10 characters of the string. The results of running this script are written to the user’s page.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object and load it with a name.
var myString = new String("Mr. R. Allen Wyke");
// Grab the first 11 characters of the string.
var mySubString = myString.substring(0,10);
// Write the results to the page.
document.write('The first 10 characters of our string, ' + myString);
document.write(', are: ' + mySubString);
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
string.sup()
The sup()
method will convert the string it is called on to an instance of the <sup>
tag.
Listing 7.361 creates an instance of the String
object and uses the document.write()
method to write the tag to the page. The results of running this script will be the following:
<sup>Hello, World!</sup>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Write the string to the page after invoking the sup() method on it.
document.write(myString.sup());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.5+, JScript 5.5+, ECMAScript 3E+
Nav6+, IE5.5+
string.toLocaleLowerCase()
The toLocaleLowerCase()
method of an instance of a String
object converts the characters in that string to all lowercase values. This is often used when a programmer tries to evaluate a string a user has entered and does not care about case. This method differs from the toLowerCase()
method by yielding its result to the host environment’s current locale.
Listing 7.362 pops up a prompt box and asks the user to enter various case text. After the user clicks OK, the lowercase version of the string is written to the page.
<script type=“text/javascript” language="JavaScript1.5">
<!--
// Create an instance of the String object.
var myString = new String(prompt("Please enter some various case text", ""));
// Convert the text to lowercase and write it to the page.
document.write(myString.toLocaleLowerCase());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.5+, JScript 5.5+, ECMAScript 3E+
Nav6+, IE5.5+
string.toLocaleUpperCase()
The toLocaleUpperCase()
method of an instance of a String
object converts the characters in that string to all uppercase values. This is often used when a programmer is trying to evaluate a string a user has entered, and case is not an issue. This method differs from the toUpperCase()
method by yielding its result to the host environment’s current locale.
Listing 7.363 pops up a prompt box and asks the user to enter various case text. After the user clicks OK, the uppercase version of the string is written to the page.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String(prompt("Please enter some various case text", ""));
// Convert the text to uppercase and write it to the page.
document.write(myString.toLocaleUpperCase());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
string.toLowerCase()
The toLowerCase()
method of an instance of a String
object converts the characters in that string to all lowercase values. This is often used when a programmer tries to evaluate a string a user has entered and does not care about case.
Listing 7.364 pops up a prompt box and asks the user to enter various case text. After the user clicks OK, the lowercase version of the string is written to the page.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String(prompt("Please enter some various case text", ""));
// Convert the text to lowercase and write it to the page.
document.write(myString.toLowerCase());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.3+, JScript 3.0+, ECMAScript 2E+
Nav4.06+, IE4+
string.toSource()
String.toSource()
The toSource()
method of the String
object will return something similar to the following:
function String() { [native code] }
If it is invoked on an instance of the String
object, it will contain the source of the instance you created.
Listing 7.365 creates an instance of the String
object. The toSource()
method is then applied to the instance and the results are written to the page. A seconddocument.write()
method writes the results of applying the method to the core object.
The result of this application of the method should be something similar to the following:
(new String(<Hello, World!>))
<script type=“text/javascript” language="JavaScript1.3">
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Apply the toSource() method to the instance and the core String
// object.
document.write(myString.toSource() + '<br>'),
document.write(String.toSource());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.1+, JScript1.0+, ECMAScript 1E+
Nav3+, NES2+, IE3+
string.toString()
String.toString()
The toString()
method of the String
object, if invoked on the core String
object, will return the object type or the name of the constructor that created the object. This will be something similar to the following:
function String() { [native code] }
If it is invoked on an instance of the String
object, it will contain the source string of the instance you created.
Listing 7.366 creates an instance of the String
object. The toString()
method is then applied to the instance and the results are written to the page. A seconddocument.write()
method writes the results of applying the method to the core object.
The result of this application of the method should be something similar to the following:
Hello, World!
<script type=“text/javascript” language="JavaScript1.3">
<!--
// Create an instance of the String object.
var myString = new String("Hello, World!");
// Apply the toString() method to the instance and the core String
// object.
document.write(myString.toString() + '<br>'),
document.write(String.toString());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
string.toUpperCase ()
The toUpperCase()
method of an instance of a String
object converts the characters in that string to all uppercase values. This is often used when a programmer is trying to evaluate a string a user has entered, and case is not an issue.
Listing 7.367 pops up a prompt box and asks the user to enter various case text. After the user clicks OK, the uppercase version of the string is written to the page.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String(prompt("Please enter some various case text", ""));
// Convert the text to uppercase and write it to the page.
document.write(myString.toUpperCase());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.2+
Nav4+, NES3+
string.unwatch (property)
The unwatch()
method of the String
object, is used to turn off the watch on a particular property specified by property.
Listing 7.368 shows how the unwatch()
method is used to stop watching the user-defined property p.
<script type=“text/javascript”>
<!--
// Create a function to handle watch.
function alertme(id, oldValue, newValue){
document.writeln("ID (" + id + ") changed from " + oldValue + " to ");
document.writeln(newValue + "<br>");
return newValue;
}
// Create instance of string.
var myString = new String();
// Create property for string.
String.prototype.p = 1;
// Watch property value.
myString.watch(“p”, alertme);
// Change value.
myString.p = 2;
// Turn off watch.
myString.unwatch(“p”);
myString.p = 3;
// -->
</script>
JavaScript 1.1+, JScript 3.0+, ECMAScript 1E+
Nav3+, NES2+, IE4+, Opera3+
string.valueOf()
The valueOf()
method returns the primitive value of the object. In terms of an instance of a String
object, this method returns the string itself.
In Listing 7.369, an instance of the String
object is created. Because the valueOf()
method returns the actual value of the string, "Here is some random text"
is written to the user’s page.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Create an instance of the String object.
var myString = new String("Here is some random text.");
// Write the value of the string to the page.
document.write('The value of my string instance is: ' + myString.valueOf());
// Close the stream to the window.
document.close();
//-->
</script>
JavaScript 1.2+
Nav4+, NES3+
string.watch(property)
The watch()
method of the String
object, is used to turn on the watch on a particular property specified by property.
Listing 7.370 shows how the watch()
method is used to start watching the user-defined property p.
<script type=“text/javascript”>
<!--
// Create a function to handle watch.
function alertme(id, oldValue, newValue){
document.writeln("ID (" + id + ") changed from " + oldValue + " to ");
document.writeln(newValue + "
");
return newValue;
}
// Create instance of string.
var myString = new String();
// Create property for string.
String.prototype.p = 1;
// Watch property value.
myString.watch(“p”, alertme);
// Change value.
myString.p = 2;
// -->
</script>
JavaScript 1.1+
Nav3+, NES2+
sun
The sun
object allows you to access any class within the package sun.*
. It is shorter and works the same way as using the Packages.sun
property.
Listing 7.371 shows how the sun
property can be used to determine whether the current browser supports the sun package
if Java is installed.
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Checks to see if the sun Java package is installed.
if(sun){
document.write ("This browser has the sun package");
}else{
document.write ("This browser does not have the sun package");
}
// -->
</script>
JavaScript 1.3+
Nav4.06+, NES3+,
Reserved Keyword
The super
keyword was reserved for future use but has not currently been implemented.
No example can be provided because super
has not been implemented.
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
switch(expression){
case label1:
code;
break;
case label2:
code;
break;
case labelN:
code;
break;
default:
code;
}
The switch
statement allows you to process the expression passed by matching it with a label—from label1 to labelN. If there is a match, the code following that label is executed. If the expression passed does not match a label, the default
section is executed. Note that you can have as many labels as you deem necessary in your script.
Listing 7.372 has a text field and a button. Users are asked to enter a day of the week into the field. When they press the button, a function is called that contains a switch
,
which verifies they entered a correct day. If so, an alert box pops up and tells users what part of the week they entered.
<html>
<head>
<title>Using the switch statement</title>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Display an alert box that contains the value of the
// submit button.
function verifyDay(form){
// Read the text entered in a variable and convert it to uppercase.
var myEntry = form.day.value.toUpperCase();
// Define what you return.
var firstPart = "You have entered a day at the beginning of the week";
var endPart = "You have entered a day at the end of the week";
var weekEnd = "you have entered a weekend day";
// Use a switch statement to perform your processing.
switch(myEntry){
case “MONDAY” :
alert(firstPart);
break;
case “TUESDAY” :
alert(firstPart);
break;
case “WEDNESDAY” :
alert('You have entered a “hump” day'),
break;
case“THURSDAY” :
alert(endPart);
break;
case “FRIDAY” :
alert(endPart);
break;
case “SATURDAY” :
alert(weekEnd);
break;
case “SUNDAY” :
alert(weekEnd);
break;
default :
alert('You have entered an invalid day'),
}
}
//-->
</script>
</head>
<body>
<form name=“myForm”>
<b>Please enter a day of the week:</b><br>
<input type=“text” value="" name=“day”>
<input type=“button” value=“Verify” name=“myButton”
onClick='verifyDay(this.form)'>
</form>
</body>
</html>
JavaScript 1.2+, JScript3.0+
Nav4+, NES3+, IE4+
Reserved Keyword
The synchronized
keyword has not been implemented in JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE2+, Opera3+
this
this.property
The this
keyword is used to refer to the current object and is often used to pass entire objects, such as those contained in Form
instances, to functions and methods specified in scripts.
Listing 7.373 contains a text box, a text area, and a button. When the user clicks the button, an onClick
event handler passes the form’s information, using the this
keyword, to a function defined in the <head>
of the document. The function opens a second, smaller window and writes several properties of the form to the page.
<html>
<head>
<title>Using this in passing form information</title>
<script type=“text/javascript”>
<!--
function displayInfo(form){
// Open a window to store the results.
var myWin = open("", "","width=450,height=200");
// Write the text boxes properties to the window.
myWin.document.write("The defaultValue of the text box is: ");
myWin.document.write(form.myText.defaultValue);
myWin.document.write("<br>The name of the text area is: ");
myWin.document.write(form.myTextArea.name);
myWin.document.write("<br>The value of the button is: ");
myWin.document.write(form.myButton.value);
// Close the stream to the window.
myWin.document.close();
}
//-->
</script>
</head>
<body>
<form name=“myForm”>
<textarea name=“myTextArea” rows=2 cols=50>
Here is some text in my text area.
</textarea>
<br>
<input type=“text” value="Change Me?" name=“myText”>
<br>
<input type=“button” value="Display Information" name=“myButton”
onClick='displayInfo(this.form)'>
</form>
</body>
</html>
Listing 7.374 creates a vehicle
object that has three properties: number of doors, color, and the type of vehicle. The this
keyword is used to associate these properties with the object when it is referenced in other scripts. Further down in the example, an instance of the vehicle
object is created and its properties are written to the page.
<html>
<head>
<title>Using this in object creation</title>
<script type=“text/javascript”>
<!--
// Create vehicle object.
function vehicle(nDoors, sColor, sType){
// Define the characteristics of the vehicle and associate
// them with a new instance using the “this” keyword.
this.doors = nDoors;
this.color = sColor;
this.type = sType;
}
//-->
</script>
</head>
<body>
<script type=“text/javascript”>
<!--
// Create an instance of the vehicle.
var myVehicle = new vehicle(4, “red”, “Toyota”);
// Call the properties of your object using the dot convention
// found throughout JavaScript.
document.writeln("I have created a " + myVehicle.type);
document.writeln(" that is " + myVehicle.color);
document.writeln(" and has " + myVehicle.doors + " doors.");
//-->
</script>
</body>
</html>
JavaScript 1.4+, JScript 5.0+, ECMAScript 3E+
Nav6+, NES3+, IE5+
throw exception
The throw
element of the JavaScript language was a reserved keyword in the JavaScript 1.3 and JScript 3.0 languages and in the Netscape Enterprise server 3 environment. Netscape 6 and Internet Explorer 5 were the first browsers to implement the keyword. It is used to generate an error condition handled by a try..catch
statement or to pass errors found in these statements to higher-level handlers.
Listing 7.375 contains a text box and button. The user is asked to insert a numeric value into the text box and press the button. When this is done, the onClick
event handler of the button calls a function to check whether the entered text was numeric. If it is not, the myErrorHandler
function is called to handle the error. The myErrorHandler
function contains a try..catch
statement that allows the programmer to define what happens on an incorrect entry. In this example, an alert
box is displayed containing an error code and message.
<html>
<head>
<title>Using throw in a try..catch statement</title>
<script type=“text/javascript” language="JavaScript1.5">
<!--
// Declare a function to handle errors.
function myErrorHandler(data){
try{
// Check to see if the value passed is “string” or “NaN”
// then “throw” the appropriate error.
if(data == “string”){
throw “E0”;
}else{
throw “E1”;
}
}catch(e){
// If the error thrown was “E0” then return the following.
if(e == “E0”){
return("Error (" + e + "): Entry must be numeric.");
}else{
// Pass off to a higher level handler.
return("Error (" + e + "): Entry must be numeric.");
}
}
}
// This function reads in the form data and calls the appropriate error.
function processData(form){
// Check to see if a number was passed.
if(isNaN(parseInt(form.myText.value))){
alert(myErrorHandler(“string”));
}else{
alert("You have correctly entered a number");
}
}
//-->
</script>
</head>
<body>
<form name=“myForm”>
Please enter a number:
<input type=“text” size=“10” value="" name=“myText”>
<input type=“button” value=“Process” name=“myButton”
onClick='processData(this.form)'>
</form>
</body>
</html>
JavaScript 1.2+
Nav4, NES3+
Reserved Keyword
The throws
keyword has not been implemented in JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.2+
Nav4+, NES3+
Reserved Keyword
The transient
keyword has not been implemented in JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.2+
Nav4+, NES3+
Reserved Keyword
The true
keyword has not been implemented in JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JScript 5.0+, JavaScript 1.4, ECMAScript 3E+
Nav6+, NES3+, IE5+
try{
statement1
throw exception;
}catch(exception if expression){
statement2
throw exception;
}catch(exception){
statement3
throw exception;
}finally{
statement4
throw exception;
}
The try…catch…finally
statement of the JavaScript language contained the try
,catch
, and finally
reserve keywords in the JavaScript 1.3 and JScript 3.0 languages and in the Netscape Enterprise server 3 environments. Internet Explorer 5 and Netscape 6 were the first browsers to implement this feature.
This statement, of which both catch
and finally
elements are optional and can contain additional nested try…catch…finally
statements, can be used to handle all or some of the errors that can occur in a script. If an error is not handled by the statement, it is passed on so other statements can handle the error. If there are no other statements to handle the error, it is passed to the browser to handle. This usually means a pop-up dialog box to the user or writing the information to a hidden error dialog.
As soon as an error occurs, the value thrown is passed to the catch
clause via exception. If the error cannot be handled, another throw
statement is used to pass the error to a higher-level (or next in line) handler if one has been defined.
statement1 is initially where an error can occur. If an if
statement is used in the catch
clause,exception is only caught if expression is true, at which time statement2 is used to handle the error. If it is not handled,statement3 will be evaluated to handle the exception. As mentioned, if no block can handle the exception, it is passed back to the browser. The finally
block, which is optional, is executed before this is done.
Listing 7.376 contains a text box and button. The user is asked to insert a numeric value into the text box and click the button. When this is done, the onClick
event handler of the button calls a function to check whether the entered text was numeric. If it is not, the myErrorHandler
function is called to handle the error. The myErrorHandler
function contains a try…catch…finally
statement that allows the programmer to define what happens on an incorrect entry. In this example, an alert
box is displayed containing an error code and message; and a second alert box is popped up, within thefinally
block, to signal the end of the error processing.
Two levels of error handling are contained in this example to demonstrate nested usage.
<html>
<head>
<script type=“text/javascript” language="JavaScript1.5">
<!--
// Declare a function to handle errors.
function myErrorHandler(data){
try{
try{
// Check to see if the value passed is “string” or “NaN”
// then “throw” the appropriate error.
if(data == “string”){
throw “E0”;
}else{
throw “E1”;
}
}catch(e){
// If the error thrown was “E0” then return the following.
if(e == “E0”){
return("Error (" + e + "): Entry must be numeric.");
}else{
// Pass off to a higher level handler.
throw e;
}
}
// This is the higher level handler for demonstration purposes.
}catch(e){
return("Error (" + e + "): Entry was invalid.");
}finally{
alert("Error processing complete!");
}
}
// This function reads in the form data and calls the appropriate error.
function processData(form){
// Check to see if a number was passed.
if(isNaN(parseInt(form.myText.value))){
alert(myErrorHandler(“string”));
}else{
alert("You have correctly entered a number");
}
}
//-->
</script>
</head>
<body>
<form name=“myForm”>
Please enter a number:
<input type=“text” size=“10” value="" name=“myText”>
<input type=“button” value=“Process” name=“myButton”
onClick='processData(this.form)'>
</form>
</body>
</html>
JavaScript 1.1+, JScript 1.0+
Nav3+, NES2+, IE3+, Opera3+
typeof (variable)
The typeof
unary operator is used to determine the type of the variable passed to it. The return values of this operator are boolean
, number
, object
, string
, or undefined
.
Listing 7.377 creates boolean
, number
, object
, string
, and undefined
variable instances, and then uses the typeof
operator to write their types to the page.
<html>
<head>
<title>Using typeof to determine the type of variables
</title>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Declare 4 variables of different types.
var bMyVar = true;
var nMyVar = 35;
var sMyVar = "This is a string";
var uMyVar;
//-->
</script>
</head>
<body>
<script type=“text/javascript” language=“JavaScript1.1”>
<!--
// Declare 4 variables of different types.
document.writeln("bMyVar = " + typeof(bMyVar));
document.writeln("<br>nMyVar = " + typeof(nMyVar));
document.writeln("<br>sMyVar = " + typeof(sMyVar));
document.writeln("<br>uMyVar = " + typeof(uMyVar));
//-->
</script>
</body>
</html>
JavaScript 1.3+, JScript 5.0+, ECMAScript 1E+
Nav4.06+, IE5+
undefined
The undefined
property is a primitive value of the Global
object. It is returned by variables that have not had values assigned to them. It is also returned by methods if the variable being evaluated is not assigned a value. Browsers not supporting this property return null
on the undefined variables.
Listing 7.378 creates the variable myVariable
, and then checks to see whether it is undefined in an if
statement. Note that Opera 3 and later browsers, even though they do not officially support this property, return null
but evaluate the if
statement in this example as true
.
<script type=“text/javascript” language="JavaScript1.3">
<!--
// Create a variable.
var myVariable;
// Evaluate the variable in an if statement and write its
// value to the page.
if(myVariable == undefined){
document.write("This variable is undefined at the moment");
}else{
document.write("This variables value is: " + myVariable);
}
//-->
</script>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
unescape (string)
The unescape()
method takes a hexadecimal value and returns the ISO-Latin-1 ASCII equivalent. This method performs the opposite operation of the escape()
method and is commonly used to escape user-entered data before form submission.
Listing 7.379 declares a local variable, escapedVal
, and passes it to the unescape()
method. The result, "@"
, is then written to the page.
<script type=“text/javascript”>
<!--
// Create a variable.
var escapedVal = "%40";
// Evaluate the variable and place the value in a variable.
var unescapedVal = unescape(escapedVal);
document.write('The <I>escapedVal</I> value (' + escapedVal + ") ");
document.write("evaluates to " + unescapedVal);
//-->
</script>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
var variable
var variable = value
The var
keyword is used to declare variables within a script. If it is used in a function, the scope of the variable is confined to that function. If used outside of a function, it is not limited and can be accessed anywhere on the page.
Listing 7.380 declares the variable, myVar
, in three different locations. It is declared once at a global level, once within a function where it is the returned value, and once in a function where it is written to the page.
<html>
<head>
<title>Examples of the var Keyword</title>
<script type=“text/javascript”>
<!--
// Declare a global variable.
var myVar = “Global”;
// Declare a variable of the same name in this function
// and return it.
function myFunc(){
var myVar = “Function”;
return myVar;
}
// Declare a variable of the same name in a second function
// and write it to the page.
function mySecFunc(){
var myVar = "Second Function";
document.write("<br>The value of myVar when called by mySecFunc() is: ");
document.write(myVar);
}
//-->
</script>
</head>
<body>
<script type=“text/javascript”>
<!--
// Write the value of the global variable.
document.write("The value of myVar when called is: " + myVar)
// Write the value returned by the function.
document.write("<br>The value of myVar when called by myFunc() is: ");
document.write(myFunc());
// Call the second function to write its results.
mySecFunc();
//-->
</script>
</body>
</html>
JScript 3.0+
var variable = new VBArray(vbarray)
The VBArray
object provides access to Visual Basic safeArrays
. These arrays are often written on the same HTML page and are written in VBScript. Table 7.45 lists the methods of the VBArray
object.
Listing 7.381 calls a VBScript function from a JScript new
operator to create a Visual Basic safe array. The function itself writes the contents of this two-dimensional array to the user’s page.
<script type="text/vbscript">
' Define the VB Array
Function myVBArray()
' Define variables for 2-D array positioning
Dim i
Dim j
' Define variable to hold incremented values to put into
' array and assign it an initial value of 1
Dim k
k = 1
' Create a 2-D array
Dim myArray(1, 1)
' Iterate through 2-D array and put incremented value in
For i = 0 To 1
For j = 0 To 1
myArray(j, i) = k
' Write the value to the screen
document.writeln(k)
k = k + 1
Next
document.writeln("<br>")
Next
' Return the array to the calling function
myVBArray = myArray
End Function
</script>
<script type="text/jscript">
<!--
// Create a new instance of VBArray
var myArray = new VBArray(myVBArray());
//-->
</script>
JScript 3.0+
vbarray.dimensions()
The dimensions()
method of an instance of a VBArray
returns the number of dimensions of the array.
Listing 7.382 calls a VBScript function from a JScript new
operator to create a Visual Basic safe array. The array itself writes the contents of this two-dimensional array to the user’s page. An alert box is also invoked that contains the number of dimensions of the array.
<script type="text/vbscript">
' Define the VB Array
Function myVBArray()
' Define variables for 2-D array positioning
Dim i
Dim j
' Define variable to hold incremented values to put into
' array and assign it an initial value of 1
Dim k
k = 1
' Create a 2-D array
Dim myArray(1, 1)
' Iterate through 2-D array and put incremented value in
For i = 0 To 1
For j = 0 To 1
myArray(j, i) = k
' Write the value to the screen
document.writeln(k)
k = k + 1
Next
document.writeln("<br>")
Next
' Return the array to the calling function
myVBArray = myArray
End Function
</script>
<script type="text/jscript">
<!--
// Create a new instance of VBArray.
var myArray = new VBArray(myVBArray());
alert(myArray.dimensions());
//-->
</script>
JScript 3.0+
vbarray.getItem(index)
vbarray.getItem(indexA, indexB, …, indexN)
The getItem()
method of an instance of a VBArray
returns the value at the index
passed. If the array is multidimensional, you pass the necessary coordinates to access the location you want.
Listing 7.383 calls a VBScript function from a JScript new
operator to create a Visual Basic safe array. The array itself writes the contents of this two-dimensional array to the user’s page. An alert box is also invoked that contains the value in the second column of the second row.
<script type="text/vbscript">
' Define the VB Array
Function myVBArray()
' Define variables for 2-D array positioning
Dim i
Dim j
' Define variable to hold incremented values to put into
' array and assign it an initial value of 1
Dim k
k = 1
' Create a 2-D array
Dim myArray(1, 1)
' Iterate through 2-D array and put incremented value in
For i = 0 To 1
For j = 0 To 1
myArray(j, i) = k
' Write the value to the screen
document.writeln(k)
k = k + 1
Next
document.writeln("<br>")
Next
' Return the array to the calling function
myVBArray = myArray
End Function
</script>
<script type="text/jscript">
<!--
// Create a new instance of VBArray.
var myArray = new VBArray(myVBArray());
alert(myArray.getItem(1,1));
//-->
</script>
JScript 3.0+
vbarray.lbound(dimension)
vbarray.lbound()
The lbound()
method of an instance of a VBArray
returns the lowest index value in the dimension passed. If no dimension is passed, the method defaults to using 1.
Listing 7.384 calls a VBScript function from a JScript new
operator to create a Visual Basic safe array. The array itself writes the contents of this two-dimensional array to the user’s page. An alert box is also invoked that contains the lowest index number used in the second dimension.
<script type="text/vbscript">
' Define the VB Array
Function myVBArray()
' Define variables for 2-D array positioning
Dim i
Dim j
' Define variable to hold incremented values to put into
' array and assign it an initial value of 1
Dim k
k = 1
' Create a 2-D array
Dim myArray(1, 1)
' Iterate through 2-D array and put incremented value in
For i = 0 To 1
For j = 0 To 1
myArray(j, i) = k
' Write the value to the screen
document.writeln(k)
k = k + 1
Next
document.writeln("<br>")
Next
' Return the array to the calling function
myVBArray = myArray
End Function
</script>
<script type="text/jscript">
<!--
// Create a new instance of VBArray.
var myArray = new VBArray(myVBArray());
alert(myArray.lbound(2));
//-->
</script>
JScript 3.0+
vbarray.toArray()
The toArray()
method of an instance of a VBArray
returns a valid JScript array from a VBArray
.
Listing 7.385 calls a VBScript function from a JScript new
operator to create a Visual Basic safe array. The array itself writes the contents of this two-dimensional array to the user’s page. The array is then converted into a valid JScript array and an alert box is invoked to display a value in this array.
<script type="text/vbscript">
' Define the VB Array
Function myVBArray()
' Define variables for 2-D array positioning
Dim i
Dim j
' Define variable to hold incremented values to put into
' array and assign it an initial value of 1
Dim k
k = 1
' Create a 2-D array
Dim myArray(1, 1
' Iterate through 2-D array and put incremented value in
For i = 0 To 1
For j = 0 To 1
myArray(j, i) = k
' Write the value to the screen
document.writeln(k)
k = k + 1
Next
document.writeln("<br>")
Next
' Return the array to the calling function
myVBArray = myArray
End Function
</script>
<script type="text/jscript">
<!--
// Create a new instance of VBArray.
var myArray = new VBArray(myVBArray());
// Convert the VBArray to a JScript Array.
var myJSArray = myArray.toArray();
// Display the second column, first row value
alert(myJSArray[0,1]);
//-->
</script>
JScript 3.0+
vbarray.ubound(dimension)
The ubound()
method of an instance of a VBArray
returns the highest index value in the dimension
passed.
Listing 7.386 calls a VBScript function from a JScript new
operator to create a Visual Basic safe array. The array itself writes the contents of this two-dimensional array to the user’s page. An alert box is also invoked that contains the highest index number used in the second dimension.
<script type="text/vbscript">
' Define the VB Array
Function myVBArray()
' Define variables for 2-D array positioning
Dim i
Dim j
' Define variable to hold incremented values to put into
' array and assign it an initial value of 1
Dim k
k = 1
' Create a 2-D array
Dim myArray(1, 1)
' Iterate through 2-D array and put incremented value in
For i = 0 To 1
For j = 0 To 1
myArray(j, i) = k
' Write the value to the screen
document.writeln(k)
k = k + 1
Next
document.writeln("<br>")
Next
' Return the array to the calling function
myVBArray = myArray
End Function
</script>
<script type="text/jscript">
<!--
// Create a new instance of VBArray.
var myArray = new VBArray(myVBArray());
alert(myArray.ubound(2));
//-->
</script>
JavaScript 1.1+, JScript 1.0+, ECMAScript 1E+ Nav3+, NES2+, IE3+
void(expression)
void expression
The void
operator is used to evaluate an expression without returning a value. This operator returns undefined
and is commonly used in place of the onClick
event handler because of various bugs in early Unix Navigator browsers. Note that Opera browsers do not support this operator.
In Listing 7.387, the void
operator is used to keep an <a>
link on a page from clicking through anywhere while still invoking the function specified.
<html>
<head>
<title>Examples of the void Operator</title>
<script type=“text/javascript”>
<!--
// Define a function to be called by clicking the link.
function myFunc(){
alert("You clicked the link!");
}
//-->
</script>
</head>
<body>
<a HREF="javascript:void(myFunc())">Click here to call the function</A>
</body>
</html>
JavaScript 1.2+ Nav4+, NES3+
Reserved Keyword
The volatile
keyword has not been implemented in JavaScript to date. It has been reserved for future use.
This keyword has not been implemented; therefore, no example is provided.
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
while(condition){
code;
}
The while
conditional statement evaluates the condition passed and executes the code within the block until the condition is no longer met. This is often used to evaluate the value of variables, and then perform tasks as well as to iterate through lines in a file when implemented on the server-side.
Listing 7.388 defines a number and then asks the user for a second number. The user is continually asked for the second number until a number lower than the defined number is entered.
<html>
<head>
<title>Using while</title>
</head>
<body>
<script type=“text/javascript”>
<!--
// Define the number to compare against and ask the user for a guess.
var indexNum = 30;
var guess = parseInt(prompt("Please enter a number.", ""));
// As long as the user puts in a higher number, keep prompting.
while(guess >= indexNum){
guess = parseInt(prompt("Try again. Guess lower!", ""));
}
// Once the user guesses a number lower than the indexed number
// write the following to the screen.
document.write('You have guessed a number lower than the index number. '),
document.write('You guessed ' + guess + ' and the index was '),
document.write(indexNum + '.'),
// Close the stream to the browser.
document.close();
//-->
</script>
</body>
</html>
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+ Nav2+, NES2+, IE3+, Opera3+
with(object){
code;
}
The with
statement takes an object
and refers to all the properties, methods, and events of that object within the code without directly referencing the object itself. This allows you to use these characteristics of an object, such as the Math
object, without specifically referencing the object.
Listing 7.389 creates a variable, and then assigns it and the methods called on it, as a Math
object. Because the with
statement is used, you do not have to reference the methods via the instance of this object.
<script type=“text/javascript”>
<!--
// Define the variables we are going to use.
var myNum = 25;
var myE, mySin, mySqrt;
// Use a with statement to use the methods of the Math object.
with (Math) {
myE = E;
mySqrt = sqrt(myNum)
mySin = sin(PI/myNum)
}
//-->
</script>
3.14.79.63