04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5: Reference Types<br />

In this code, the string “ yellow ” is compared to three different values: “ brick ” , “ yellow ” , and “ zoo ” .<br />

Because “ brick ” comes alphabetically before “ yellow ” , localeCompare() returns 1 ; “ yellow ” is<br />

equal to “ yellow ” , so localeCompare() returns 0 for that line; and “ zoo ” comes after “ yellow ” , so<br />

localeCompare() returns – 1 for that line. Once again, because the values are implementation - specific,<br />

it is best to use localeCompare() as shown in this example:<br />

function determineOrder(value) {<br />

var result = stringValue.localeCompare(value);<br />

if (result < 0){<br />

alert(“The string ‘yellow’ comes before the string ‘” + value + “’.”);<br />

} else if (result > 0) {<br />

alert(“The string ‘yellow’ comes after the string ‘” + value + “’.”);<br />

} else {<br />

alert(“The string ‘yellow’ is equal to the string ‘” + value + “’.”);<br />

}<br />

}<br />

determineOrder(“brick”);<br />

determineOrder(“yellow”);<br />

determineOrder(“zoo”);<br />

By using this sort of construct, you can be sure that the code works correctly in all implementations.<br />

The unique part of localeCompare() is that an implementation ’ s locale (country and language)<br />

indicates exactly how this method operates. In the United States, where English is the standard language<br />

for ECMAScript implementations, localeCompare() is case - sensitive, determining that uppercase<br />

letters come alphabetically after lowercase letters. However, this may not be the case in other locales.<br />

The fromCharCode() Method<br />

There is one method on the String constructor: fromCharCode() . This method ’ s job is to take one or<br />

more character codes and convert them into a string. Essentially, this is the reverse operation from the<br />

charCodeAt() instance method. Consider this example:<br />

alert(String.fromCharCode(104, 101, 108, 108, 111)); //”hello”<br />

In this code, fromCharCode() is called on a series of character codes from the letters in the word<br />

“ hello ” .<br />

HTML Methods<br />

The web - browser vendors recognized a need early on to format HTML dynamically using JavaScript.<br />

As a result, they extended the specification to include several methods specifically designed to aid in<br />

common HTML formatting tasks. The following table enumerates the HTML methods. However, be<br />

aware that typically these methods aren ’ t used, because they tend to create nonsemantic markup.<br />

141

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!