Localize Strings in Javascript

前端 未结 12 1612
长发绾君心
长发绾君心 2020-11-28 05:52

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 Ja

12条回答
  •  天命终不由人
    2020-11-28 06:04

    I did the following to localize JavaScript for a mobile app running HTML5:

    1.Created a set of resource files for each language calling them like "en.js" for English. Each contained the different strings the app as follows:

    
            var localString = {
            appName: "your app name",
            message1: "blah blah"
          };
    

    2.Used Lazyload to load the proper resource file based on the locale language of the app: https://github.com/rgrove/lazyload

    3.Pass the language code via a Query String (As I am launching the html file from Android using PhoneGap)

    4.Then I wrote the following code to load dynamically the proper resource file:

    
    var lang = getQueryString("language");
    localization(lang);
    function localization(languageCode) {
        try {
            var defaultLang = "en";
            var resourcesFolder = "values/";
            if(!languageCode || languageCode.length == 0)
                languageCode = defaultLang;
            // var LOCALIZATION = null;
            LazyLoad.js(resourcesFolder + languageCode + ".js", function() {
                if( typeof LOCALIZATION == 'undefined') {
                    LazyLoad.js(resourcesFolder + defaultLang + ".js", function() {
                        for(var propertyName in LOCALIZATION) {
                            $("#" + propertyName).html(LOCALIZATION[propertyName]);
                        }
                    });
                } else {
                    for(var propertyName in LOCALIZATION) {
                        $("#" + propertyName).html(LOCALIZATION[propertyName]);
                    }
                }
            });
        } catch (e) {
            errorEvent(e);
        }
    }
    function getQueryString(name)
    {
      name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
      var regexS = "[\\?&]" + name + "=([^&#]*)";
      var regex = new RegExp(regexS);
      var results = regex.exec(window.location.href);
      if(results == null)
        return "";
      else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    

    5.From the html file I refer to the strings as follows:

    
        span id="appName"
    

提交回复
热议问题