Main Page

Detecting language using JavaScript

Detecting language using JavaScript
In Chapter 5, “JavaScript in the Browser,” you were introduced to the
object and its proper-
ties. One of the properties that has not been discussed in detail is the
property, which returns
the language and country code in which the browser is currently operating (for example, “en-us” for
United States English):
var sLang = navigator.language; //won’t work in IE
Mozilla, Opera, and Safari/Konqueror all support this property, but Internet Explorer does not.
Instead, Internet Explorer provides three properties:
(indicates the language being
used by the browser),
(essentially identical to
), and
(indicating the language of the operating system). The
property is essentially the same as
, so you can make a simple addition to the previous code to detect the language for all
var sLang = navigator.language || navigator.browserLanguage;
Using this code, you can determine if someone is viewing your page from a browser with an unsupported
language setting and take appropriate action, such as redirecting the visitor to a more appropriate page:
if (sLang.toLowerCase() == “fr”) {
This code checks to see if the language is French (represented as
), and if so, it redirects to another page.
The most important step in internationalizing your JavaScript is to avoid hard-coded strings. For example,
don’t do this:
alert(“The date you entered is incorrect.”);
In this example, the string
“The date you entered is incorrect.”
is hard-coded. When a value is
hard-coded, its value cannot be changed without directly editing the line that uses it. Compare this with
the following example:
var sIncorrectDateMessage = “The date you entered is incorrect.”;
//more code here
You may have noticed that this code uses
on the language string.
This is necessary because capitalization is not consistent across browsers. Some
report United States English as
, whereas others use
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 569

JavaScript EditorFree JavaScript Editor     Ajax Editor