There is a JavaScript function, escape, that encodes an entire string, converting ASCII to URL Encoding (ISO Latin-1 [ISO 8859-1]), which can be used in HTML processing. This is particularly important if you’re processing data for web applications.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Convert Object to String</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <script type="text/javascript"> //<![CDATA[ var sOne = escape("http://oreilly.com"); document.writeln("<p>" + sOne + "</p>"); var sTwo = escape("http://burningbird.net/index.php?pagename=$1&page=$2"); document.writeln("<p>" + sTwo + "</p>"); //]]> </script> </body> </html>
The result of the program is the following two escaped strings:
http%3Aoreilly.com http%3Aburningbird%2Cnet/index.php%3Fpagename%3D%241%26page%3D%242
Characters that are escaped are spaces, colons, slashes, and other characters meaningful in an HTML context. To return the string to the original, use the unescape function on the modified string.
Though handy enough, the problem with escape is that it doesn’t work with non-ASCII characters. There are, however, two functions encodeURI and decodeURI that provide encoding beyond just the ASCII character set. The encoding that’s followed is shown in Table 2-4, replicated from the Mozilla Core JavaScript 1.5 Reference.
| Type 1 | Includes |
|---|---|
| Reserved characters | ; , / ? : @ & = + $ |
| Unescaped characters | Alphabetic, decimal digits, - _ . ! ~ * ’ ( ) |
| Score | # |
var sURL = "http://oreilly.com/this_is_a_value&some-value='some value'"; sURL = encodeURI(sURL); document.writeln("<p>" + sURL + "</p>");
Here’s the resulting string printed to the page:
http://oreilly.com/this_is_a_value&some-value=‘some%20va
You can also explicitly convert a variable to a string using string (toString in ECMAScript). If the value being converted is a boolean, the resulting string is a text representation of the Boolean value: “true” for true; “false” for false. For numbers, the string is, again, a string representation of the number, such as “123.06” for 123.06, depending on the number of digits and the precision (placement of the decimal point). A value of NaN (Not a Number, discussed later) returns “NaN”.
The boolean data type has two values: true and false. They are not surrounded by quotes; in other words, “false” is not the same as false.
The function Boolean (ToBoolean in ECMAScript) can convert another value to boolean true or false.
Numbers in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don’t have a decimal point or fractional component, they’re treated as integers base-10 whole numbers in a range of 253 to 253.
You can convert strings or booleans to numbers; two functions, parseInt and parseFloat, manage the conversion depending on the type of number you want returned.
The parseInt function returns the integer portion of a number in a string, whether the string is formatted as an integer or floating point. The parseFloat function returns the floating-point value until a nonnumeric character is reached. Below, three strings containing numeric values are passed to either parseInt or parseFloat, and the values are written to the page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Convert String to Number</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <p> <script type="text/javascript"> //<![CDATA[ var sNum = "1.23e-2"; document.writeln(parseFloat(sNum)); var fValue = parseFloat("1.45inch"); document.writeln("<p>" + fValue + "</p>"); var iValue = parseInt("33.00"); document.writeln("<p>" + iValue + "</p>"); //]]> </script> </p> </body> </html>
Using Firefox as a browser, the values printed out are:
0.0123 1.45 33
Notice with the first value, the number is printed out in decimal notation rather than the exponential notation of the original string value. Also note that parseInt truncates the fractional component of the number.
The parseInt function can convert an octal or hexadecimal number back to base-10 representation. There is a second parameter to the function, base, which is 10 or base 10, by default. If any other base is specified, in a range from 2 to 36, the string is interpreted accordingly. If you replace the document output JavaScript in Example 2-3 with the following:
var iValue = parseInt("0266",8); document.writeln("<p>" + iValue + "</p>"); var iValue = parseInt("0x5F",16); document.writeln("<p>" + iValue + "</p>");
These octal and hexidecimal values are printed out to the page:
182
95
The division between literals, simple data types, and objects is blurred in JavaScript, nowhere more so then when looking at two that represent nonexistence or incomplete existence: null and undefined.
A null variable is one that has been defined, but hasn’t been assigned a value. The following is an example of a null variable:
alert(sValue); // results in JavaScript // error because sValue is not declared first
In this example, the variable sValue has not not been declared either through the use of the var keyword or by being passed as a parameter to a function. If the variable has been declared but not initialized, it is considered undefined.
var sValue; alert(sValue); // no error, and a window // with the word 'undefined' is opened
A variable is not null and not undefined when it is both declared and given an initial value:
var sValue = "";
When using several JS libraries and fairly complex code, it’s not unusual for a variable to not get set, and trying to use it in an expression can have adverse effectsusually a JavaScript error. One approach to test variables if you’re unsure of their state is to use the variable in a conditional test, such as the following:
if (sValue) ... // if not null and initialized, // expression is true; otherwise false
We’ll look at conditional statements in the next chapter, but the expression consisting of just the variable sValue evaluates to TRue if sValue has been declared and initialized; otherwise, the result of the expression is false:
if (sValue) // not true, as variable has // not been declared, and is therefore null
var sValue; if (sValue) // variable is not null, but it's // not true, as variable has not been defined (initialized with a value)
var sValue = 1; if (sValue) // true now, as variable has been set, // which automatically declares it
Using the null keyword, you can specifically test to see whether a value is null:
if (sValue == null)
In JavaScript, a variable is undefined, even if declared, until it is initialized. It differs from null in that using a null value as a parameter to a function results in an error, while using an undefined variable usually does not:
alert(sValue); // JS error results, "Error: sValue is not defined" var sValue; // no JS error and the window reads, "undefined" // which is the value of the object
A variable can be undeclared but initialized, in which case it is not null and not undefined. However, in this instance, it’s considered a global variable, and as discussed earlier, not specifically declaring variables with var causes problems more often than not.
Though not related to existence, there is a third unique value related to the type of a variable: NaN, or Not A Number. If a string or Boolean variable cannot be coerced into a number, it’s considered NaN and treated accordingly:
var nValue = 1.0; if (nValue == 'one' ) // false, the second operand is NaN
You can specifically test whether a variable is NaN with the isNaN function:
if (isNaN(sValue)) // if string cannot be implicitly // converted into number, // return true
In other words, zero, null, NaN, and the empty string are inherently false; everything else is inherently true.