Well, first of all, if you’re looking for country names, you should ask, “What country are you from?” Otherwise people might answer what state or province they’re from or what city they’re from. (You might also want to say, “What country do you currently reside in?”, since “What country are you from?” could be interpreted to mean, “What country were you born in?”, “What country did you grow up in?”, or “What country do you currently reside in?”, which could all be different answers.)
If your responses depend on specific country names, then you could create an array of country names, and then search the string for those names. For example, you could put this in your JavaScript section:
setup.countries = ["Europe", "France", "United States of America", ..., "United States", "America", "USA", "US"];
setup.getCountry = function (txt) {
for (var i = 0; i < setup.countries.length; i++) {
if (txt.toLowerCase().indexOf(setup.countries[i].toLowerCase()) > -1) {
return setup.countries[i]; // Return country name
}
}
return txt; // Country not found
};
The .toLowerCase()
method will make sure that the search ignores any capitalization issues. Also, because setup.countries
and setup.getCountry
won’t change, they’re put on the setup
object variable so that they’ll be accessible from both JavaScript and SugarCube code and won’t waste space in the game’s history.
Note that, when you fill in the rest of the country names (where the “…” part is), you’ll want to put any country names which could be a subset of another country’s name, such as how “US” is a subset of “Belarus”, at the end of the list. Generally the rule should be that longer names go in the front of the array, and smaller ones at the end.
Keep in mind though, that this code is pretty simple and may get “false positives”. If they type in “my house”, then it will find the “US” in “house” and return “US” as the country name. If that will be a problem, then you’ll need to modify the code to make sure it isn’t finding the name within other words.
Also, if the getCountry()
function doesn’t find a country name, then it will just return the original string. You could change that if you want to be able to tell when a country name isn’t found. (Just change the “return txt;
” line into something like “return 'unknown';
” instead.)
Now, for example, if the text to be searched is in a variable named _response
, then you could get the country name like this:
<<set $country = setup.getCountry(_response)>>
That said, a far simpler solution would be to use the <<listbox>>
macro, and have it contain a list of country names they could pick from. There are also trickier solutions, where you could have the code attempt to guess the country name being typed in, and have that appear in a dropdown below the text entry line. If you were going to do that, I’d recommend using something like the jQuery UI Autocomplete Widget.
Hope that helps! 