HTML and CSS Reference
In-Depth Information
Using the split() Method of the String Object The split() method is used
to split a string based on an identified separator and a desired number of “sub” strings.
The split() method searches the string object for the separator, which is enclosed within
the quotation marks, and for every separator creates a separate sub string. These values
are stored in an array. An array is a JavaScript object that stores multiple values in one
variable name. Arrays are discussed in detail in Chapter 11. Table 10-21 shows the general
form of the split() method.
Table 10-21 split() Method
General form: var newValue = stringname.split (separator, how many)
where newValue Is a variable holding the results of the split; stringname is any string object;
separator is a string value such as a space, comma, or period that can separate a string; and
how many is the value that indicates how many items will result from the split.
numbparts[0] contains 555
numbparts[1] contains 543
numbparts[2] contains 4321
In this chapter, the split() method is used to separate the dollars from the cents at
the decimal point in the monthly payment amount. Figure 10-27 provides an example of
how the split() method works.
Value of monthly payment as valuein: 659.49
formatAmt = valuein.split(".",2)
dollar amount placed
in formatAmt[0]
indicates where
to split value at
decimal point
Value of formatAmt[0] after split: 659
Value of formatAmt[1] after split 49
cents placed in
Figure 10-27
Beginning the dollarFormat() Function and Formatting the Dollars
Portion The dollarFormat() function initializes the variables that will be used to format
value as currency. Most programmers agree it is a good programming practice to clear and
initialize variables to ensure the data is valid. Table 10-22 shows the JavaScript code used
to add the dollarFormat() function.
Table 10-22 Code for the dollarFormat() Function
function dollarFormat(valuein) {
var formatValue = “”
var formatDollars = “”
formatAmt = valuein.split(“.”,2)
var dollars = formatAmt[0]
Line 74 declares the dollarFormat() function and the valuein variable. Lines 75 and
76 clear the variables used to assemble the formatted output by assigning null (or empty)
values. The split() method in line 77 returns the dollar portion of the value and the cents
portion into an array called formatAmt. As an array, formatAmt[0] contains the dollar
amount, and formatAmt[1] contains the cents. Line 78 assigns the dollar amount to the
dollars variable.
Search WWH ::

Custom Search