HTML and CSS Reference
In-Depth Information
x and y locations, whereas the substr() method uses a length value to extract y number
of characters starting at x location. Table 9-13 describes the substr() method. To extract
the year 2014 from the string using the substr() method, the JavaScript code would be
written as:
birthDay.substr(yearLocate, 4)
Table 9-13 substr() Method
General form:
var variable=string.substr(x,y)
Comment:
where string is any string object instance. This method extracts a portion of a string, starting at
location x for a length of y . x and y may be constants or variables.
Example:
var dayofweek = today.toLocaleString() //Converts date into string as: Day, Month Date,
Year HH:MM:SS AM/PM
yearLocate=dayofweek.indexOf(“2014”)
year=dayofweek.substr(yearLocate, 4)
Result:
the variable year contains the four-digit year
Both the substring() and substr() methods use relative addressing as a means of
locating characters in a string. A relative address is the location of a byte in a string of
bytes, as defined by its position relative to the first byte in that string. As an example,
assume the data in Table 9-14 is a string value stored in the variable birthDay. The address
of the first byte in a string of characters is zero (0).
Table 9-14 Relative Addressing
S u n d a y ,
M a r c h
9 ,
2 0 1 4
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Table 9-15 shows the JavaScript code used to extract the system date for the
Midwest Bridal Expo Web page. The JavaScript code uses the toLocaleString(), substr(),
substring(), and indexOf() methods of the Date() object to obtain the current system date
and then extract the weekday, the date, the month, and the year. Once these values have
been extracted and assigned to variables, they can be displayed on the Web page.
Table 9-15 Code to Extract the System Date
Line
Code
8
function countDown() {
9
var today = new Date()
10
var dayofweek = today.toLocaleString()
11
dayLocate = dayofweek.indexOf(“ “)
12
weekDay = dayofweek.substring(0, dayLocate)
13
newDay = dayofweek.substring(dayLocate)
14
dateLocate = newDay.indexOf(“,”)
15
monthDate = newDay.substring(0, dateLocate+1)
17
yearLocate = dayofweek.indexOf(“2014”)
18
year = dayofweek.substr(yearLocate, 4)
Line 8 starts the JavaScript user-defined function, countDown(). The function must
include the open brace. Line 9 creates the new date object instance variable, today, and
assigns the current system date and time to the variable. Line 10 converts the date and
 
Search WWH ::




Custom Search