Localize Strings in Javascript

SaaS Developer picture SaaS Developer · Sep 19, 2008 · Viewed 47.6k times · Source

I'm currently using .resx files to manage my server side resources for .NET.

the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings?

Ideally, I would like to store the strings in the .resx files to keep them with the rest of the localized resources.

I'm open to suggestions.

Answer

Joel Anair picture Joel Anair · Sep 19, 2008

A basic JavaScript object is an associative array, so it can easily be used to store key/value pairs. So using JSON, you could create an object for each string to be localized like this:

var localizedStrings={
    confirmMessage:{
        'en/US':'Are you sure?',
        'fr/FR':'Est-ce que vous êtes certain?',
        ...
    },

    ...
}

Then you could get the locale version of each string like this:

var locale='en/US';
var confirm=localizedStrings['confirmMessage'][locale];