Math.SQRT2

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

   math.SQRT2

Description

The SQRT2 property of the Math object returns the value of the square root of 2. This is approximately equal to 1.414.

Example

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.

Listing 7.256 Example of the SQRT2 Property

<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>

Math.tan()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

   math.tan (num)

Description

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.

Example

Listing 7.257 shows how the tan() method is used.

Listing 7.257 Example of the tan() Method

<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>

Math.toSource()

JavaScript 1.3+

Nav4.06+

 

Syntax

   math.toSource()

Description

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.

Example

Listing 7.258 shows how the toSource() method is used to make a copy of the Math object.

Listing 7.258 Example of the toSource() Method

<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>

Math.toString()

JavaScript 1.0+, JScript 3.0+

Nav2+, NES2+, IE4+

 

Syntax

   math.toString()

Description

The toString() method of the Math object returns a string value representing the object.

Example

Listing 7.259 shows how the toString() method is used to get a string value representing the Math object.

Listing 7.259 Example of the toString() Method

<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>

Math.unwatch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

   math.unwatch (prop)

Description

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.

Example

All math properties are read-only; therefore, no example can be provided.

Math.watch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

   math.watch( prop, handler )

Description

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.

Example

Math properties are read-only; therefore, no example is provided.

NaN

JavaScript 1.3+, JScript 1.0+

Nav4.06+, IE3+

 

Syntax

   NaN

Description

The NaN object represents an object that is not equal to any number, including itself. NaN stands for Not a Number.

Example

Listing 7.260 shows how the NaN object is used within a comparison.

Listing 7.260 Example Using the NaN Object

<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>

native

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

   Reserved Keyword

Description

The native keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented, therefore no example is provided.

netscape

JavaScript 1.1+

Nav3+, NES2+, Opera3+

 

Syntax

   netscape

Description

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.

Example

Listing 7.261 shows how the netscape property can be used to determine whether the current browser supports the netscape package.

Listing 7.261 Example Using the netscape Object

<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>

new

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

   new

Description

The new operator is used to create a new object.

Example

Listing 7.262 shows how new is used to create a new Array object.

Listing 7.262 Example of new

<html>
<body>

<script type=“text/javascript” language=“JavaScript”>
<!--

// Creates a new array object with the name myArray.
var myArray = new Array();

// -->
</script>

</body>
</html>

null

JavaScript 1.2+, JScript 3.0+, ECMAScript 1.0+

Nav4+, NES3+, IE4+

 

Syntax

   Reserved Keyword

Description

The null keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

Number()

JavaScript 1.2+, ECMAScript 1.0+

Nav4+, NES3+, IE5+

 

Syntax

   Number (obj)

Description

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.

Example

Listing 7.263 shows an example of the Number() method. A new Date object is created and converted to a number.

Listing 7.263 Example Number() Method

<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>

Number()

JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

   var variable = new Number(value)

Description

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.

Table 7.40 Properties and Methods of the Number() Object

Image

Example

Listing 7.264 shows how a new Number object is created.

Listing 7.264 Example of the Number Constructor

<html>
<body>

<script type=“text/javascript” language=“JavaScript”>
<!--
// Creates a new number object.

var aNum = new Number(3);
// -->
</script>

</body>
</html>

Number.constructor

JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+

Nav3+, NES2+, IE4+

 

Syntax

   Number.constructor

Description

The constructor property of the Number object specifies the function that creates the object.

Example

Listing 7.265 shows an example of the constructor property.

Listing 7.265 Example Number 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>

Number.MAX_VALUE

JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

   Number.MAX_VALUE

Description

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.

Example

Listing 7.266 shows how the MAX_VALUE property is used.

Listing 7.266 Example of the MAX_VALUE Property

<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>

Number.MIN_VALUE

JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

   Number.MIN_VALUE

Description

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.

Example

Listing 7.267 shows how the MIN_VALUE property is used.

Listing 7.267 Example of MIN_VALUE

<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>

Number.NaN

JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

   Number.NaN

Description

The NaN property of the Number object represents a value that is not equal to any numeric value.

Example

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.

Listing 7.268 Example of the NaN Property

<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>

Number.NEGATIVE_INFINITY

JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

   Number.NEGATIVE_INFINITY

Description

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.

Example

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.

Listing 7.269 Example of 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>

Number.POSITIVE_INFINITY

JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

   Number.POSITIVE_INFINITY

Description

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.

Example

Listing 7.270 shows how the POSITIVE_INFINITY property is used.

Listing 7.270 Example of POSITIVE_INFINITY

<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>

Number.prototype

JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

   Number.prototype.property

   Number.prototype.method

Description

The prototype property of the Number object allows you to add properties or methods to all instances of this class.

Example

Listing 7.271 shows how the prototype property is used.

Listing 7.271 Example of prototype

<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>

Number.toExponential()

JavaScript 1.3+, ECMAScript 3E+

Nav6+, IE5.5+

 

Syntax

   number.toExponential()

Description

The toExponential()method of the Number object is used to get an exponential representation of the Number object.

Example

Listing 7.272 shows how the toExponential() method is used.

Listing 7.272 Example of the toExponential() Method

<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>

Number.toFixed()

JavaScript 1.4+, ECMAScript 3E+

Nav6+, IE5.5+

 

Syntax

   number.toFixed(num)

Description

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.

Example

Listing 7.273 shows how the toFixed() method is used to get the fixed form of the standard Number object.

Listing 7.273 Example of the toFixed() Method

<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>

Number.toLocaleString()

JavaScript 1.4+, ECMAScript 3E+, JScript 1.0+

Nav6+, IE5.5+, Opera5+

 

Syntax

   number.toLocaleString()

Description

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.

Example

Listing 7.274 shows how the toLocaleString() method is used to display the string value of myNum.

Listing 7.274 Example of the toLocaleString() Method

<script type=“text/javascript” language=“JavaScript”>
<!--

var myNum = 123456789;
// Get the string value and display.
document.write("The Locale String is: " + myNum.toLocaleString() );

// -->
</script>

Number.toPrecision()

JavaScript 1.4+, ECMAScript 3E+

Nav6+, IE5.5+

 

Syntax

   number.toPrecision(num)

Description

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.

Example

Listing 7.275 shows how the toPrecision() method is used.

Listing 7.275 Example of the toPrecision() Method

<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>

Number.toSource()

JavaScript 1.3+, ECMAScript 1E+

Nav4.06+

 

Syntax

   number.toSource()

Description

The toSource()method of the Number object is used to get a string representation of the Number object.

Example

Listing 7.276 shows how the toSource() method is used.

Listing 7.276 Example of the toSource() Method

<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>

Number.toString()

JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

   number.toString()

Description

The toString() method of the Number object is used to get a string representation of the Number object.

Example

Listing 7.277 shows how the toString() method is used.

Listing 7.277 Example of the toString() Method

<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>

Number.unwatch()

JavaScript 1.1+, JScript 3.0+

Nav3+, NES2+, IE4+

 

Syntax

   number.unwatch(prop)

Description

The unwatch() method of the Number object will remove a watch point on a property set by the watch() method.

Example

Listing 7.278 shows an example for the unwatch() method.

Listing 7.278 Example of 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>

Number.valueOf()

JavaScript 1.1+, JScript 2.0+

Nav3+, NES2+, IE4+

 

Syntax

number.valueOf()

Description

The valueOf() method of the Number object is used to get the primitive value of a Number object as a number data type.

Example

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.

Listing 7.279 Example of the Number.valueOf() Method

<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>

Number.watch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

number.watch(prop, handler)

Description

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.

Example

Listing 7.280 shows an example for the watch() method.

Listing 7.280 Example of 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>

Object()

JavaScript 1.1+, ECMAScript 1E+, JScript1.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

var variable = new Object(string)

Description

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.

Table 7.41 Properties/Methods of the Object() Object

Image

Example

Listing 7.281 shows how the Object object is used.

Listing 7.281 Example of the Object Object

<html>
<body>

<script type=“text/javascript” language=“JavaScript”>
<!--
// Create an Object.
var myObj = new Object(foo);
document.write(Object foo created);
// -->
</script>

</body>
</html>

Object.constructor

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+ Nav3+, NES2+, IE4+

 

Syntax

object.constructor

Description

The constructor property of the Object object specifies the function that creates the object.

Example

Listing 7.282  shows an example of the constructor property.

Listing 7.282 Example Object 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>

Object.eval()

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES2+, IE4+

 

Syntax

object.eval (string)

Description

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.

Example

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.

Listing 7.283 Example of the eval() Method

<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>

Object.prototype

JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+

Nav3+, NES2+, IE4+

 

Syntax

object.prototype.property

object.prototype.method

Description

The prototype property of the Object object allows the addition of properties or methods to the Object class.

Example

Listing 7.284 shows how the prototype property is used.

Listing 7.284 Example of the prototype Property

<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>

Object.toSource()

JavaScript 1.3+

Nav4.06+

 

Syntax

object.toSource()

Description

The toSource() method is used to get a string representation of the object.

Example

Listing 7.285 shows how the toSource() is used.

Listing 7.285 Example of the toSource() Method

<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>

Object.toString()

JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+

Nav3+, NES2+, IE4+, Opera3+

 

Syntax

object.toString()

Description

The toString() method is used to get a string representation of the Number object.

Example

Listing 7.286 shows how the toString() method is used.

Listing 7.286 Example of the toString() Method

<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>

Object.unwatch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

object.unwatch (prop)

Description

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.

Example

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.

Listing 7.287 Example of the unwatch() Method

<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>

Object.valueOf()

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES2+, IE4+, Opera3+

 

Syntax

object.valueOf()

Description

The valueOf()method for the Object object is used to obtain the value of the specified object.

Example

Listing 7.288 shows how the valueOf() method is used.

Listing 7.288 Example of the valueOf() Method

<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>

Object.watch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

object.watch(propfunction)

Description

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.

Example

Listing 7.289 shows how the watch() method is used.

Listing 7.289 Example of the watch() Method

<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>

package

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Reserved Keyword

Description

The package keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

Packages

JavaScript 1.1+

Nav3+, NES2+

Syntax

Packages.packagename

Description

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.

Table 7.42 Properties of the Packages Object

Image

Example

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.

Listing 7.290 Example of the Packages Object

<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>


Packages.className

JavaScript 1.1+

Nav3+, NES2+

 

Syntax

Packages.className

Description

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.

Example

Listing 7.291 shows an example for accessing a fictitious class using the className property.

Listing 7.291 Example of Packages.className

<html>
<body>
<script type=“text/javascript” language=“JavaScript”>
<!--

// Access the class: myClass.
myName = new Packages.myClass.Car()

//  -->
</script>

</body>
</html>

Packages.java

JavaScript 1.1+

Nav3+, NES2+

 

Syntax

Packages.java.className.methodName

Description

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.

Example

Listing 7.292 shows an example for the java sub-package. It is used to write text to the Java Console.

Listing 7.292 Example of the Packages.java Sub-package

<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>

Packages.netscape

JavaScript 1.1+

Nav3+, NES2+

 

Syntax

Packages.netscape.className.methodName

Description

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.

Example

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.

Listing 7.293 Example of Accessing the netscape Package

<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>

Packages.sun

JavaScript 1.1+

Nav3+, NES2+

 

Syntax

Packages.sun.className.methodName

Description

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.

Example

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.

Listing 7.294 Example of Accessing the sun Package

<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>

parseFloat()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

paraseFloat (string)

Description

The parseFloat() function is used to convert a string to a number.

Example

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.

Listing 7.295 Example of the parseFloat() Method

<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>

parseInt()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

parseInt(string, radix)
parseInt(string)

Description

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.

Example

Listing 7.296 shows how parseInt() is used to parse a string. A few different examples are shown for different types of strings.

Listing 7.296 Example of the parseInt() Method

<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>

private

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Reserved Keyword

Description

The private keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

protected

JavaScript 1.2

Nav4+, NES3+

 

Syntax

Reserved Keyword

Description

The protected keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

public

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Reserved Keyword

Description

The public keyword has not been implemented in server-side JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

RegExp()

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

var variable = new RegExp(patternflags)

Description

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.

Table 7.43 Properties and Methods of the RegExp() Object

Image

Example

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.

Listing 7.297 Example of the RegExp Object

<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>

RegExp,$*

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

RegExp, $*

Description

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.

Example

Listing 7.298 shows how to use RegExp,$* for pattern matching.

Listing 7.298 Example of RegExp,$*

<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>

RegExp.$&

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

RegExp.$&

Description

The RegExp.$& property represents the last matched characters. This is the same as using the lastMatch property.

Example

Listing 7.299 shows how RegExp.$& is used.

Listing 7.299 Example of RegExp.$&

<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>

RegExp,$_

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

RegExp,$ _

Description

The RegExp,$_ property represents the input to which a string is matched. This is the same as using the input property.

Example

Listing 7.300 shows how to use the RegExp,$_ property.

Listing 7.300 Example of RegExp,$_

<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>

RegExp.$`

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

RegExp.$`

Description

The RegExp.$` property represents the substring preceding the most recent pattern match. This is the same as using the leftContext property.

Example

Listing 7.301 shows how to use RegExp.$`.

Listing 7.301 Example of 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>

RegExp.$`

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

RegExp.$'

Description

The RegExp.$' property represents the substring following the most recent pattern match. This is the same as using the rightContext property.

Example

Listing 7.302 shows how to use RegExp.$'.

Listing 7.302 Example of 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>

RegExp.$+

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

RegExp.$+

Description

The RegExp.$+ property represents the last parenthesized substring pattern match. This is the same as using the lastParen property.

Example

Listing 7.303 shows how RegExp.$+ is used.

Listing 7.303 Example of RegExp.$+

<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>

RegExp.$1,$2,..$9

JavaScript 1.2+, JScript 1.0+

Nav4+, NES3+, IE4+

 

Syntax

RegExp.$1,$2,..$9

Description

The RegExp.$1,$2,..$9 property represents parenthesized substring matches.

Example

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.

Listing 7.304 Example of RegExp.$1,$2,..$9

<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>

RegExp.constructor()

JavaScript 1.1+, JScript 3.0+

Nav3+, NES2+, IE4+, Opera5+

 

Syntax

regexp.constructor

Description

The constructor property of the RegExp object specifies the function that creates the object.

Example

Listing 7.305 shows how the constructor property is used to create a RegExp object.

Listing 7.305 Example of the constructor Property

<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>

RegExp.compile()

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

regexp.compile(patternflag)

Description

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).

Example

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.

Listing 7.306 Example of the compile() Method

<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>

RegExp.exec()

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

regexp.exec  (string)

Description

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.

Example

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.

Listing 7.307 Example of 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>

RegExp.global

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

regexp.global

Description

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.

Example

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.

Listing 7.308 Example of the global Property

<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>

RegExp.ignoreCase

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

regexp.ignoreCase

Description

The ignoreCase property of the RegExp object is a flag that informs the user whether case is to be ignored during pattern matching.

Example

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.

Listing 7.309 Example of ignoreCase

<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>

RegExp.input

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

regexp.input

Description

The input property of the RegExp object represents the string on which the pattern matching is performed.

Example

Listing 7.310 shows how to use the input property.

Listing 7.310 Example of 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>

RegExp.lastIndex

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

regexp.lastIndex

Description

The lastIndex property of the RegExp object is used to get the index of where the next match begins.

Example

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.

Listing 7.311 Example of lastIndex

<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>

RegExp.lastMatch

JavaScript 1.2+, JScript 5.5+

Nav4+, NES3+, IE4+

 

Syntax

regexp.lastMatch

Description

The lastMatch property of the RegExp object represents the last matched characters.

Example

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.

Listing 7.312 Example of the lastMatch Property

<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>

RegExp.lastParen

JavaScript 1.2+, JScript 5.5+

Nav4+, NES3+, IE4+

 

Syntax

regexp.lastParen

Description

The lastParen property of the RegExp object represents the last parenthesized substring match. It returns a string value for the last parenthesized substring.

Example

Listing 7.313 shows how the lastParen property is used.

Listing 7.313 Example of the lastParen Property

<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>

RegExp.leftContext

JavaScript 1.2+, JScript 5.5+

Nav4+, NES3+, IE4+

 

Syntax

regexp.leftContext

Description

The leftContext property of the RegExp object represents the substring preceding the most recent pattern match.

Example

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.

Listing 7.314 Example of the leftContext Property

<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>

RegExp.multiline

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

regexp.multiline

Description

The multiline property of the RegExp object is used to determine whether pattern matching should be performed across multiple lines.

Example

Listing 7.315 shows how multiline is used.

Listing 7.315 Example of multiline

<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>

RegExp.prototype

JavaScript 1.1+

Nav3+, NES2+, Opera4+

 

Syntax

regexp.prototype.property
regexp.prototype.method

Description

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.

Example

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.

Listing 7.316 Example of the prototype Property for RegExp Object

<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>

RegExp.rightContext

JavaScript 1.2+, JScript 5.5+

Nav4+, NES3+, IE4+

 

Syntax

regexp.rightContext

Description

The rightContext property of the RegExp object represents the substring following the most recent pattern match.

Example

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.

Listing 7.317 Example of rightContext

<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>

RegExp.source

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

regexp.source

Description

The source property of the RegExp object represents the text of the pattern being used for pattern matching.

Example:

Listing 7.318 shows how the source property can be used to get the pattern being matched.

Listing 7.318 Example of the source Property

<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>

RegExp.test()

JavaScript 1.2+

Nav4+, NES3+, IE4+

 

Syntax

regexp.test()

Description

The test() method of the RegExp object is used to test for a pattern match in a string. Returns boolean value true or false.

Example

Listing 7.319 shows how the test() method is used.

Listing 7.319 Example of the test() Method

<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>

RegExp.toSource()

JavaScript 1.3+, ECMAScript 1E+

Nav4.06+

 

Syntax

regexp.toSource()

Description

The toSource() method of the Number object is used to get a string representation of the Number object.

Example

Listing 7.320 shows how the toSource() method is used.

Listing 7.320 Example of the toSource() Method

<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>

RegExp.toString()

JavaScript 1.1+, ECMAScript 1E+

Nav3+, NES2+, IE4+, Opera3+

 

Syntax

regexp.toString()

Description

The toString() method of the RegExp object is used to get a string representation of the RegExp object.

Example

Listing 7.321 shows how the toString() method is used.

Listing 7.321 Example of the toString() Method

<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>

RegExp.unwatch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

regexp.unwatch(prop)

Description

The unwatch() method of the RegExp object will remove a watch point on a property set by the watch() method.

Example

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.

Listing 7.322 Example of the unwatch() Method

<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>

RegExp.valueOf()

JavaScript 1.1+

Nav3+, NES2+, IE4+

 

Syntax

regexp.valueOf()

Description

The valueOf() method of the RegExp object is used to get the primitive value of a RegExp object as a number data type.

Example

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.

Listing 7.323 Example of the RegExp.valueOf() Method

<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>

RegExp.watch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

regexp.watch(prop, handler)

Description

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.

Example

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.

Listing 7.324 Example of the watch() Method

<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>

return

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

return

Description

The return keyword will exit the existing function and return a value.

Example

Listing 7.325 shows an example of using the return statement to return the value of the processing from the function.

Listing 7.325 Example of return

<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>

ScriptEngine

JScript 2.0+

 

Syntax

ScriptEngine()

Description

The ScriptEngine() function has three possible return values: JScript, VBScript, and VBA. When implemented in JavaScript scripts, this function returns JScript.

Example

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.

Listing 7.326 Using the ScriptEngine Function to Retrieve Information About the Version of the Scripting Engine in an Internet Explorer Browser

<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>

ScriptEngineBuildVersion

JScript 2.0+

 

Syntax

ScriptEngineBuildVersion

Description

The ScriptEngineBuildVersion() function contains the actual build number of the scripting engine contained on the user’s machine.

Example

Listing 7.327 prints the build number of the scripting engine interpreting the script.

Listing 7.327 Using the ScriptEngineBuildVersion Function to Retrieve the Build Number of the Scripting Engine in an Internet Explorer Browser

<script type="text/jscript">
<!--

// Write the build number to the page
document.write("Build " + ScriptEngineBuildVersion());

//-->
</script>

ScriptEngineMajorVersion

JScript 2.0+

 

Syntax

ScriptEngineMajorVersion()

Description

The ScriptEngineMajorVersion() function contains the actual major version number of the scripting engine contained on the user’s machine.

Example

Listing 7.328 prints the major version number of the scripting engine interpreting the script.

Listing 7.328 Using the ScriptEngineMajorVersion Function to Retrieve the Major Version Number of the Scripting Engine in an Internet Explorer Browser

<script type="text/jscript">
<!--

// Write the build number to the page
document.write("Major Version: " + ScriptEngineMajorVersion());

//-->
</script>

ScriptEngineMinorVersion

JScript 2.0+

 

Syntax

ScriptEngineMinorVersion()

Description

The ScriptEngineMinorVersion() function contains the actual minor version number of the scripting engine contained on the user’s machine.

Example

Listing 7.329 prints the minor version number of the scripting engine interpreting the script.

Listing 7.329 Using the ScriptEngineMinorVersion Function to Retrieve the Minor Version Number of the Scripting Engine in an Internet Explorer Browser

<script type="text/jscript">
<!--

// Write the build number to the page.
document.write("Minor Version: " + ScriptEngineMinorVersion());

//-->
</script>

short

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Reserved Keyword

Description

The short keyword has not been implemented in JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

static

JavaScript 1.2+

Nav4+, NES3+,

 

Syntax

Reserved Keyword

Description

The static keyword has not been implemented in JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

String (Function)

JavaScript 1.2+, JScript 3.0+, ECMAScript 1E+

Nav4+, NES3+, IE4+, Opera4+

 

Syntax

String (var)

Description

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.

Example

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.

Listing 7.330 Using the String() Function

<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>

String (Object)

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

var variable = new String(string) JavaScript1.1+
“string”

Description

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.

Table 7.44 Properties and Methods Used by the String Object

Image

Image

Image

Example

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.

Listing 7.331 Examples of an Instance of the String Object

<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>

String.anchor()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.anchor(name)

Description

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.

Example

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>

Listing 7.332 Using the anchor() Method of the String Object

<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>

String.big()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.big()

Description

The big() method will convert the string it is called on to an instance of the <big> tag.

Example

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>

Listing 7.333 Using the big() Method of the String Object

<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>

String.blink()

JavaScript 1.0+

Nav2+, NES2+

 

Syntax

string.blink()

Description

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.

Example

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>

Listing 7.334 Using the blink() Method of the String Object

<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>

String.bold()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.bold()

Description

The bold() method will convert the string it is called on to an instance of the <bold>tag.

Example

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>

Listing 7.335 Using the bold() Method of the String Object

<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>

String.charAt()

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.charAt(num)

Description

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.

Example

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.

Listing 7.336 Using the charAt() Method to Retrieve a Character at a User-specified Location in a String


<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>

String.charCodeAt()

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.charCodeAt(num)

Description

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.

Example

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.

Listing 7.337 Using the charCodeAt() Method to Retrieve a Character at a User-specified Location in a String

<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>

String.concat()

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

string.concat(string2)

Description

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.

Example

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.

Listing 7.338 Using the concat() Method to Concatenate Two Strings

<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>

String.constructor

JavaScript 1.1+, JScript 3.0+, ECMAScript 1E+

Nav3+, NES2+, IE4+, Opera3+

 

Syntax

string.constructor

Description

The constructor property of the String object specifies the function that creates the object.

Example

Listing 7.339 shows an example of the constructor property, which is used to check the type of variable.

Listing 7.339 Example of the constructor Property

<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>

String.fixed()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.fixed()

Description

The fixed() method will convert the string it is called on to an instance of the <tt>tag.

Example

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>

Listing 7.340 Using the fixed() Method of the String Object

<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>

String.fontcolor()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.fontcolor (hexnum
string.fontcolor(color)

Description

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.

Example

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>

Listing 7.341 Using the fontcolor() Method of the String Object

<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>

String.fontsize()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.fontsize(num)
string.fontsize(string2)

Description

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.

Example

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>

Listing 7.342 Using the fontsize() Method of the String Object

<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

String.fromCharCode()

JavaScript 1.2+, JScript 3.0+, ECMAScript 1E+

Nav4+, NES3+, IE4+

 

Syntax

String.fromCharCode(num1, num2, …, numN
String.fromCharCode(keyevent.which)

Description

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.

Example

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.

Listing 7.343 Using the fromCharCode() Method to Determine the Characters of the ISO-Latin-1 Numbers Passed


<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>

String.indexOf()

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.indexOf(stringnum
string.indexOf(string)

Description

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.

Example

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”.

Listing 7.344 Using the indexOf() Method to Find the Location of a Character in a String

<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()

 

Syntax

string.italics()

Description

The italics() method will convert the string it is called on to an instance of the <i>tag.

Example

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!

Listing 7.345 Using the italics() Method of the String Object

<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>

String.lastIndexOf()

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.lastIndexOf(stringnum)
string.lastIndexOf(string)

Description

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.

Example

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”.

Listing 7.346 Using the lastIndexOf() Method to Find the Location of a Character in a String

<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>

String.length

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.length

Description

The length property of an instance of the String object returns the total length of the string.

Example

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.

Listing 7.347 Accessing the length Property of an Instance of the String Object

<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>

String.link()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.link(URL)

Description

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.

Example

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>

Listing 7.348 Using the link() Method of the String Object

<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>

String.localeCompare()

JavaScript 1.5+, ECMAScript 3E+

Nav6

 

Syntax

string.localeCompare (string2)

Description

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.

Example

In Listing 7.349, two strings are created and the localeCompare() method is called to compare them.

Listing 7.349 Using the localeCompare() Method

<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>

String.match()

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

string.match (regexpression)

Description

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.

Example

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.

Listing 7.350 Using the match() Method to Match Regular Expressions in a String


<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>

String.prototype

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES2+, IE4+, Opera3+

 

Syntax

String.prototype.property
String.prototype.method

Description

The prototype property of the String object allows a programmer to add properties or methods to a core JavaScript object.

Example

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.

Listing 7.351 Using the prototype Property to Create New Properties and Methods of the String Object

<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>

String.replace()

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

string.replace(regexpressionreplacestring)

Description

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.

Example

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”.

Listing 7.352 Using the replace() Method to Replace Regular Expression Matches in a String

<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>

String.search()

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

string.search (regexpression)

Description

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.

Example

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.

Listing 7.353 Using the search() Method to Search Regular Expressions in a String

<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>

String.slice()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.slice(num1num2
string.slice(num)

Description

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.

Example

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.

Listing 7.354 Using the slice() Method to Return Seven Characters in a String

<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>

String.small()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.small()

Description:

The small() method will convert the string it is called on to an instance of the <small>tag.

Example

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>

Listing 7.355 Using the small() Method of the String Object

<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>

String.split()

JavaScript 1.1+, JScript 1.0+, ECMAScript 1E+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

string.split(separatornum
string.split(separator
string.split(regexpressionnum)
string.split(regexpression)

Description

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.

Example

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.

Listing 7.356 Using the split() Method to Split the String Passed into Separate Strings

<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>

String.strike()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.strike()

Description

The strike() method will convert the string it is called on to an instance of the<strike> tag.

Example

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>

Listing 7.357 Using the strike() Method of the String Object

<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>

String.sub()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

Syntax

string.sub()

Description

The sub() method will convert the string it is called on to an instance of the <sub> tag.

Example

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>

Listing 7.358 Using the sub() Method of the String Object

<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>

String.substr()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.substr(num1num2
string.substr (num)

Description

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.

Example

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.

Listing 7.359 Using the substr() Method to Return Seven Characters in a String

<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>

String.substring()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.substring(num1num2
string.substring(num)

Description

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.

Example

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.

Listing 7.360 Using the substring() Method to Return 11 Characters in a String

<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>

String.sup()

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.sup()

Description

The sup() method will convert the string it is called on to an instance of the <sup> tag.

Example

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>

Listing 7.361 Using the sup() Method of the String Object

<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>

String.toLocaleLowerCase()

JavaScript 1.5+, JScript 5.5+, ECMAScript 3E+

Nav6+, IE5.5+

 

Syntax

string.toLocaleLowerCase()

Description

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.

Example

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.

Listing 7.362 Using the toLocaleLowerCase() Method of the String Object to Convert a String Entered by a User to Lowercase

<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>

String.toLocaleUpperCase()

JavaScript 1.5+, JScript 5.5+, ECMAScript 3E+

Nav6+, IE5.5+

 

Syntax

string.toLocaleUpperCase()

Description

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.

Example

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.

Listing 7.363 Using the toLocaleUpperCase() Method of the String Object to Convert a String Entered by a User to Uppercase

<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>

String.toLowerCase()

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.toLowerCase()

Description

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.

Example

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.

Listing 7.364 Using the toLowerCase() Method of the String Object to Convert a String Entered by a User to Lowercase

<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>

String.toSource()

JavaScript 1.3+, JScript 3.0+, ECMAScript 2E+

Nav4.06+, IE4+

 

Syntax

string.toSource()
String.toSource()

Description

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.

Example

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!>))

Listing 7.365 Using the toSource() Method of the String Object to Obtain the Source of the Object or an Instance of It

<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>

String.toString()

JavaScript 1.1+, JScript1.0+, ECMAScript 1E+

Nav3+, NES2+, IE3+

 

Syntax

string.toString()
String.toString()

Description

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.

Example

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!

Listing 7.366 Using the toString() Method of the String Object to Obtain the Source of the Object or an Instance of It

<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>

String.toUpperCase()

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

string.toUpperCase ()

Description

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.

Example

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.

Listing 7.367 Using the toUpperCase() Method of the String Object to Convert a String Entered by a User to Uppercase

<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>

String.unwatch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

string.unwatch (property)

Description

The unwatch() method of the String object, is used to turn off the watch on a particular property specified by property.

Example

Listing 7.368 shows how the unwatch() method is used to stop watching the user-defined property p.

Listing 7.368 Example of unwatch() Method of the Array Object

<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>

String.valueOf()

JavaScript 1.1+, JScript 3.0+, ECMAScript 1E+

Nav3+, NES2+, IE4+, Opera3+

 

Syntax

string.valueOf()

Description

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.

Example

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.

Listing 7.369 Using the valueOf() Method to Return the Value of the

<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>

String.watch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

string.watch(property)

Description

The watch() method of the String object, is used to turn on the watch on a particular property specified by property.

Example

Listing 7.370 shows how the watch() method is used to start watching the user-defined property p.

Listing 7.370 Example of watch() Method of the Array Object

<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>

sun

JavaScript 1.1+

Nav3+, NES2+

 

Syntax

sun

Description

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.

Example

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.

Listing 7.371 Example Using the sun Object

<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>

super

JavaScript 1.3+

Nav4.06+, NES3+,

 

Syntax

Reserved Keyword

Description

The super keyword was reserved for future use but has not currently been implemented.

Example

No example can be provided because super has not been implemented.

switch

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE4+

 

Syntax

switch(expression){ 
case label1
code
break; 
case label2:
code
break; 
case labelN:
code
break; 
default: 
code;
}

Description

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.

Example

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.

Listing 7.372 Using a switch Statement to Process Data

<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>

synchronized

JavaScript 1.2+, JScript3.0+

Nav4+, NES3+, IE4+

 

Syntax

Reserved Keyword

Description

The synchronized keyword has not been implemented in JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

this

JavaScript 1.0+, JScript 1.0+

Nav2+, NES2+, IE2+, Opera3+

 

Syntax

this 
this.property

Description

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.

Example

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.

Listing 7.373 Using this to Pass All Form Data to a Function

<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.

Listing 7.374 Using this to Internally Reference Properties of a User-defined Object

<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>

throw

JavaScript 1.4+, JScript 5.0+, ECMAScript 3E+

Nav6+, NES3+, IE5+

 

Syntax

throw exception

Description

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..catchstatement or to pass errors found in these statements to higher-level handlers.

Example

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.

Listing 7.375 This Example Uses throw in a try..catch Statement

<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>

throws

JavaScript 1.2+

Nav4, NES3+

 

Syntax

Reserved Keyword

Description

The throws keyword has not been implemented in JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

transient

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Reserved Keyword

Description

The transient keyword has not been implemented in JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

true

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Reserved Keyword

Description

The true keyword has not been implemented in JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

try…catch…finally

JScript 5.0+, JavaScript 1.4, ECMAScript 3E+

Nav6+, NES3+, IE5+

 

Syntax

try{ 
statement1
throw exception
}catch(exception if expression){ 
statement2
throw exception
}catch(exception){ 
statement3
throw exception
}finally{ 
statement4
throw exception
}

Description

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 catchclause,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.

Example

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.

Listing 7.376 This Example Uses a try…catch…finally Statement to Handle an Incorrect Entry

<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>

typeof

JavaScript 1.1+, JScript 1.0+

Nav3+, NES2+, IE3+, Opera3+

 

Syntax

typeof (variable)

Description

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.

Example

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.

Listing 7.377 This Example Uses the typeof Unary Operator to Return the Types for Four Different Variables

<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>

undefined

JavaScript 1.3+, JScript 5.0+, ECMAScript 1E+

Nav4.06+, IE5+

 

Syntax

undefined

Description

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.

Example

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.

Listing 7.378 Testing a Variable to See Whether It Is undefined

<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>

unescape()

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

unescape (string)

Description

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.

Example

Listing 7.379 declares a local variable, escapedVal, and passes it to the unescape()method. The result, "@", is then written to the page.

Listing 7.379 Using the unescape() Method to Convert a Hexadecimal Value to Its ASCII Equivalent


<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>

var

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

 

Syntax

var variable
var variable = value

Description

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.

Example

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.

Listing 7.380 This Example Shows Using the var Keyword in Three Different Instances


<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>

VBArray

JScript 3.0+

 

Syntax

var variable = new VBArray(vbarray)

Description

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.

Table 7.45 Methods of the VBArray Object

Image

Example

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.

Listing 7.381 Creating a VBArray

<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>

VBArray.dimensions()

JScript 3.0+

 

Syntax

vbarray.dimensions()

Description

The dimensions() method of an instance of a VBArray returns the number of dimensions of the array.

Example

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.

Listing 7.382 Viewing the Number of Dimensions of a VBArray Object

<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>

VBArray.getItem()

JScript 3.0+

 

Syntax

vbarray.getItem(index)
vbarray.getItem(indexAindexB, …, indexN)

Description

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.

Example

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.

Listing 7.383 Using the getItem() Method

<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>

VBArray.lbound()

JScript 3.0+

 

Syntax

vbarray.lbound(dimension)
vbarray.lbound()

Description

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.

Example

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.

Listing 7.384 Using the lbound() Method

<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>

VBArray.toArray()

JScript 3.0+

 

Syntax

vbarray.toArray()

Description

The toArray() method of an instance of a VBArray returns a valid JScript array from a VBArray.

Example

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.

Listing 7.385 Using the toArray() Method

<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>

VBArray.ubound()

JScript 3.0+

 

Syntax

vbarray.ubound(dimension)

Description

The ubound() method of an instance of a VBArray returns the highest index value in the dimension passed.

Example

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.

Listing 7.386 Using the ubound() Method

<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>

void

JavaScript 1.1+, JScript 1.0+, ECMAScript 1E+ Nav3+, NES2+, IE3+

 

Syntax

void(expression)
void expression

Description

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.

Example

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.

Listing 7.387 Using the void Operator to Call a Function

<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>

volatile

JavaScript 1.2+ Nav4+, NES3+

 

Syntax

Reserved Keyword

Description

The volatile keyword has not been implemented in JavaScript to date. It has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

while

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+

Nav2+, NES2+, IE3+, Opera3+

Syntax

while(condition){
code;
}

Description

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.

Example

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.

Listing 7.388 Using the while Statement to Check the Value Passed In

<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>

with

JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+ Nav2+, NES2+, IE3+, Opera3+

 

Syntax

with(object){
code;
}

Description

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.

Example

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.

Listing 7.389 Using the with Statement

<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>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.79.63