annexare / Countries

Countries, Languages & Continents data (capital and currency, native name, calling codes).
https://annexare.github.io/Countries/
MIT License
1.16k stars 430 forks source link

getCountryCode may not return for some valid countries #137

Closed dezull closed 1 month ago

dezull commented 5 months ago

Use case for the feature

For example, getCountryCode("Cocos (Keeling) Islands") won't return the correct country code, because of the parentheses in the country name.

Examples or links

The countryName used in the RegExp in the function is not escaped, so characters such as parentheses are interpreted as special characters:

const nameRegex = new RegExp('^' + countryName + '$', 'i')

The solution in https://github.com/annexare/Countries/issues/131 can fix this, or a slight modification:

export const getCountryCode = (countryName: string): TCountryCode | false => {
  // Match exact country name, but case insensitive
  const country = countryName.toLowerCase();

  return (
    countryDataList.find(({ name, native }) =>
       country === name.toLowerCase() ||
       country === native.toLowerCase()
    )?.iso2 || false
  )
}

Maybe allowing something like "Cocos Islands" or "Keeling Islands" also makes sense?

osztenkurden commented 1 month ago

Getting name of the Myanmar (Burma) is also impossible due to this issue unfortunately

dmythro commented 1 month ago

Hi, forgot about this. Someone could've make a PR :) But looks like no volunteers. I'll check it out and update tests to make sure those countries are found properly.

dmythro commented 1 month ago

@dezull @osztenkurden please check if v3.1.1 works for you. Increased test coverage so seems fine with any name now.