string object
Whenever you assign a string value to a variable or property, you create a string object. For example, the statement
mystring = "Hello, World!"
creates a string object called mystring. String literals are also string objects; for example, the literal "Howdy" is a string object.
A string object has one predefined property, length, that indicates the number of characters in the string. So, using the previous example, the expression
x = mystring.length
assigns a value of thirteen to x, because "Hello, World!" has thirteen characters.
A string object has two kinds of methods: those that return a variation on the string itself, such as substring and toUpperCase, and those that return an HTML-formatted version of the string, such as bold and link.
For example, using the previous example, both mystring.toUpperCase()
and "hello, world!".toUpperCase()
return the string "HELLO, WORLD!"
The substring method takes two arguments and returns a subset of the string between the two arguments. Using the previous example, mystring.substring(4, 9)
returns the string "o, Wo." For more information, see the reference topic for substring.
The string object also has a number of methods for automatic HTML formatting, such as bold to create boldface text and link to create a hyperlink. For example, you could create a hyperlink to a hypothetical URL with the link method as follows:
mystring.link("http://www.helloworld.com")
Math object
The built-in Math object has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi (3.141...), which you would use in an application as
Math.PI
Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write
Math.sin(1.56)
Note that all trigonometric methods of Math take arguments in radians.
The following table summarizes Math's methods.
It is often convenient to use the with statement when a section of code uses several math constants and methods, so you don't have to type "Math" repeatedly. For example,
with (Math) {
a = PI * r*r
y = r*sin(theta)
x = r*cos(theta)
}
Date object
JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.
JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00.
Note:Currently, you cannot work with dates prior to January 1, 1970.
To create a Date object:
dateObjectName = new Date([parameters])
where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object.
The parameters in the preceding syntax can be any of the following:
today = new Date().
Xmas95 = new Date("December 25, 1995 13:30:00")
. If you omit hours, minutes, or seconds, the value will be set to zero.
Xmas95 = new Date(95,11,25)
. A set of values for year, month, day, hour, minute, and seconds. For example, Xmas95 = new Date(95,11,25,9,30,0)
.
Xmas95 = new Date("December 25, 1995")
Then Xmas95.getMonth()
returns eleven, and Xmas95.getYear()
returns ninety-five.
The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since the epoch for a Date object.
For example, the following code displays the number of days left in the current year:
today = new Date()
endYear = new Date("December 31, 1990") // Set day and month
endYear.setYear(today.getYear()) // Set year to this year
msPerDay = 24 * 60 * 60 * 1000 // Number of milliseconds per day
daysLeft = (endYear.getTime() - today.getTime()) / msPerDay
daysLeft = Math.round(daysLeft)
document.write("Number of days left in the year: " + daysLeft)
This example creates a Date object named today that contains today's date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days.
The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate object:
IPOdate = new Date()
IPOdate.setTime(Date.parse("Aug 9, 1995"))
Built-in functions
JavaScript has several "top-level" functions built in to the language. They are eval, parseInt, and parseFloat.
The eval function
The built-in function eval takes a string as its argument. The string can be any string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.
If the argument represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements.
This function is useful for evaluating a string representing an arithmetic expression. For example, input from a form element is always a string, but you often want to convert it to a numerical value.
The following example takes input in a text field, applies the eval function and displays the result in another text field. If you type a numerical expression in the first field and click the button, the expression will be evaluated. For example, enter "(666 * 777) / 3" and click the button to see the result.
<SCRIPT>
function compute(obj) {
obj.result.value = eval(obj.expr.value)
}
</SCRIPT>
<FORM NAME="evalform">
Enter an expression: <INPUT TYPE="text" NAME="expr" SIZE=20 >
<BR>
Result: <INPUT TYPE="text" NAME="result" SIZE=20 >
<BR>
<INPUT TYPE="button" VALUE="Click Me" onClick="compute(this.form)">
</FORM>
The display in Navigator looks like this:
The eval function is not limited to evaluating numerical expressions, however. Its argument can include object references or even JavaScript statements. For example, you could define a function called setValue that would take two arguments, an object and a value, as follows:
function setValue (myobj, myvalue) {
eval ("document.forms[0]." + myobj + ".value") = myvalue
}
Then, for example, you could call this function to set the value of a form element "text1" as follows:
setValue(text1, 42)
The parseInt and parseFloat functions
The two "parse" functions, parseInt and parseFloat, return a numeric value when given a string as an argument. For detailed descriptions and examples, see the reference topics.
The syntax of parseFloat is
parseFloat(str)
parseFloat parses its argument, the string str, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number).
The syntax of parseInt is
parseInt(str [, radix])
parseInt parses its first argument, the string str, and attempts to return an integer of the specified radix (base), indicated by the second, optional argument, radix. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The parseInt function truncates numbers to integer values.