Get Locale via Javascript

Since a lot of websites need to be available in multiple languages, or localized, developers need a way to figure out what language the user prefers. Most modern browsers have a setting in their preferences or options that the user can change. If the user doesn't, then the browser most likely uses the operating system's locale (language and country) setting.

There are many ways to get this information. Most server-side programming languages can get the requester's locale from the request header. However, now that many sites use AJAX or GWT, developers need to be able to get this information on the client-side, i.e. using JavaScript.

Here's an implementation that I use when it's necessary for me to get the locale on the client-side.

if ( navigator ) {
    if ( navigator.language ) {
        return navigator.language;
    }
    else if ( navigator.browserLanguage ) {
        return navigator.browserLanguage;
    }
    else if ( navigator.systemLanguage ) {
        return navigator.systemLanguage;
    }
    else if ( navigator.userLanguage ) {
        return navigator.userLanguage;
    }
}

This JavaScript should work on most modern browsers. I know that it works in Firefox 1+ and Internet Explorer 5.5+. I haven't done any more compatibility testing than that though.