Change country name to abbreviation

I am extracting some XML data containing countries, among many other things, and I would like to associate the name of the country with its abbreviation in order to match them with famfamfam flags.

See an example below:

$('Result',xml).each(function(i) { var $this = $(this), user = $this.attr("Username"), country = $this.attr("Country"), 

Thus, the country variable will get the name of the country, so how can I dynamically change 247 potential countries to reduce it.

The following is a list of abbreviations and full country names:

 >FI FINLAND >FJ FIJI >FK FALKLAND ISLANDS (MALVINAS) >FM MICRONESIA, FEDERATED STATES OF >FO FAROE ISLANDS >FR FRANCE >FX FRANCE, METROPOLITAN >GA GABON >GB UNITED KINGDOM >GE GEORGIA 
+4
source share
1 answer

You need to ask yourself the question of how the abbreviation is somehow stored in your xml answer. I assume this is not the case, in which case you will need to create an object in JavaScript, for example:

 var countryCodes = { 'NL' : 'Netherlands', 'FR' : 'France' // and all the other countries } var inverseCountryCodes = {}; for(i in countryCodes) { inverseCountryCodes[countryCodes[i]] = i; } 

Note: this actually means that you will have a huge piece of code creating an array of countryCodes, which is more or less a database. Please consider entering a separate js file called countries.js or any other, and include if as the (first) javascript file.

Now you can simply transfer from countryCode to your real name and vice versa, i.e.

 countryCodes['NL'] 

will lead to the Netherlands and

 inverseCountryCodes['France'] 

will result in "FR".

The best option would be to determine what the most stable representation for the country is, I think it will be the country code, since the names have different meanings in different languages. So you can think of returning (server side) countryCode as xml.

Anyroad, good luck!

ATTENTION:

I just found this: http://www.geonames.org/export/ws-overview.html

This is a good list of web queries you can do to get all kinds of geoinformation. countryInfo seems to do exactly the opposite of what you want, but still it can help you. For example, this way you can get information about Germany. Allowing the server to respond with code instead of a name, this may be exactly what you need!

http://api.geonames.org/countryInfoJSON?formatted=true&lang=it&country=DE&username=demo&style=full

If you will use this, do not forget to make your own api.geoname.org account, instead of using demo-username;)

+4
source

Source: https://habr.com/ru/post/1414706/


All Articles